Elektor 03 2020

Download as pdf or txt
Download as pdf or txt
You are on page 1of 116
At a glance
Powered by AI
Some of the key topics discussed in the magazine include various electronics projects, IoT solutions, vacuum tube audio equipment, and a Hexadoku puzzle.

Projects discussed include building IoT solutions with ESP8266, an open weather station, a self-balancing robot, and monitoring of solar PV cells.

The Hexadoku puzzle is a variation of Sudoku that uses hexadecimal numbers and is laid out on a 16x16 grid.

Edition 3/2020 | May & June | www.elektormagazine.

com

lektor
DESIGN SHARE SELL ELECTRONICS
magazine

Open-Network
Weather Station
Mk.2
Measure, log, stream,
multi-sensor
environmental data
to ThingSpeak,
openSenseMap

New Series Universal Triac Control


Artificial Intelligence Module with ATmega
for Beginners

Object recognition using the Maixduino board Switch and dim a variety of loads

Analogue Electronics Design BalBot: a Self-Balancing Robot BASIC for the ESP32/ESP8266 CAN Bus + Arduino for Solar PV Cell Monitoring
Elektor 1.2 GHz Multifunction Frequency Meter (1992/93) Elektor New Precise Nixie Clock Revisited How-To: GitHub For Dummies Inexpensive
E-Scooter Joy-IT HD35 Electronic USB Load My IoT Button: A Button for the Web Open-Network Weather Station Mk.2 PeakTech 6080 A
Lab Power Supply Practical ESP32 Multitasking Safe products in the IoT era SigFox and the IoT Small Circuits Revival Starting Out
in Electronics Tamper-Evident Box TMS0280 Speech Synthesizer …and more
IoT Home Hacks
with ESP8266
Description:
Ready to start building Internet of
Things (IoT) solutions? With a little
know-how and the right tools, such as
the ESP8266 Wi-Fi module, you can
design and build handy IoT solutions for
your home or office. In IoT Home Hacks
with ESP8266, Hans Henrik Skovgaard
introduces the ESP8266 – in the form
of the WeMos D1 Mini Pro – and then
covers a variety of IoT hacks that you’ll
find immediately useful.

You’ll learn to build the following and


much more!

• Colorful smart home accessory


• Refrigerator controller
• 230-V power monitor
• Door lock monitor

The custom software for the IoT devices


and PCB layouts are available for free at
Elektor.com. Order the book today!

O W6

lektor
N 31,4 rs
€ fo
r mem
be

Read more on:


www.elektor.com/iot-home-hacks-with-esp8266
Elektor Magazine,
English edition
Edition 3/2020
Volume 46, No. 501
May & June 2020

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

www.elektor.com
A well-developed
www.elektormagazine.com
network — more
Elektor Magazine, English edition important than ever!
is published 6 times a year by

Just a few weeks ago I had planned to report about the Embedded World
Elektor International Media
78 York Street 2020 trade show in this editorial space. As always, I discovered interesting
London W1H 1DP products there. But the show, held at the end of February, now seems to be a
United Kingdom thing of the distant past. In the meantime, we got used to queueing in front
Phone: (+44) (0)20 7692 8344
of supermarkets and DIY stores, and seeing our colleagues on video only.

Head Office:
On the other hand, videos from last year on the Internet now seem almost
Elektor International Media b.v. surreal to me — lectures on electronics to a closely packed audience, or music
PO Box 11 festivals with cheering crowds.
NL-6114-ZG Susteren However, life goes on. With a little creativity you can network even in these
The Netherlands
times. One of my colleagues recently celebrated his birthday using the ‘Zoom’
Phone: (+31) 46 4389444
video platform. Among his ‘guests’ were many electronics engineers, some of
whom had joined in from their lab. Personally, together with a few friends I
Memberships:
am about to broadcast a regular DJ livestream, from living rooms but properly
Please use London address equipped technically. You may also have ideas on how to continue exchanging
E-mail: [email protected] ideas with like-minded people in order to advance a common project. Elektor
www.elektor.com/memberships offers a platform for electronics projects at www.elektor-labs.com, which was
recently given a new look, a faster engine and extended functionality.
Advertising & Sponsoring: Elektor’s English edition quietly reached number 500 in March 2020 and Elek-
Margriet Debeij
tor Germany turns 50 this month. Both are unique successes in the industry,
Phone: +49 170 5505 396
E-mail: [email protected]
precisely because many readers have remained loyal to us for decades. But
especially in these times, this should not be a reason for Elektor to rest on

www.elektor.com/advertising
its laurels. On the contrary, wires and brain cells are glowing. For example, I
Advertising rates and terms available on can divulge that new offers and media formats are in active development to
request. inform all electronics technicians in an even more targeted way.
Stay tuned and above all, stay healthy!
Copyright Notice
The circuits described in this magazine are for domes-
 
tic and educational use only. All drawings, photographs, Jens Nickel
printed circuit board layouts, programmed integrated International Editor-in-Chief, Elektor Magazine
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, The Circuit
including photocopying, scanning and recording, in
whole or in part without prior written permission from International Editor-in-Chief: Jens Nickel
the Publisher. Such written permission must also be
Editor-in-Chief, English edition: Jan Buiting
obtained before any part of this publication is stored
in a retrieval system of any nature. Patent protection Membership Manager: Denise Bodrone
may exist in respect of circuits, devices, components
International Editorial Staff: Eric Bogers, Rolf Gerstendorf, Denis Meyer,
etc. described in this magazine. The Publisher does
not accept responsibility for failing to identify such Dr Thomas Scherer, Clemens Valens
patent(s) or other protection. The Publisher disclaims
any responsibility for the safe and proper function
Laboratory Staff: Mathias Claussen, Ton Giesberts,
of reader-assembled projects based upon or from Luc Lemmens, Clemens Valens, Jan Visser
schematics, descriptions or information published in or
in relation with Elektor magazine. Graphic Design & Prepress: Giel Dols

Publisher: Don Akkermans


© Elektor International Media b.v. 2020
Printed in the Netherlands

www.elektormagazine.com May & June 2020 3


This Edition Open-Network
Weather Station
Volume 47 – Edition 3/2020
No. 501 May & June 2020

Mk.2
6
Regulars
26 How-To: GitHub For Dummies
How to download something from GitHub

35 Peculiar Parts, the series


TMS0280 Speech Synthesizer Measure, log, stream,
36 Interactive multi-sensor environmental data
to ThingSpeak, openSenseMap
Corrections & Updates || Questions & Answers

42 Developer’s Zone
Tips & Tricks, Best Practices
and Other Useful Information

50 Starting Out in Electronics (3) Artificial Intelligence


for Beginners
Easier than imagined!

52 Small Circuits Revival


Capita Selecta from the
Elektor Project Suggestions Box

90 Analogue Electronics Design (3) New


Series
Case Study #1 — Section 3: Preamplifier
response optimization and trade-offs

12
98 Steeped in Electronics
Lead-free soldering and EU regulatory zeal

Object recognition using


the Maixduino board

100 Lab, Sweet Lab


A glimpse of The Holy Place —
no unauthorized entry.

104 Elektor Store Features


What’s 4 Sale @ www.elektor.com Retronics
106 Beyond Electronics 12 Artificial Intelligence for Beginners (1)
A Big Challenge: Object recognition
Elektor 1.2 GHz
safe products in the IoT era using the Maixduino board Multifunction
108 Retronics: Elektor 1.2 GHz Multifunction 81 Start-Up Update Frequency Meter
Frequency Meter (1992/93) The Elektor Investment Program
Crossing the magic 1 GHz border (1992/93)
82 Review:
114 Hexadoku Joy-IT HD35 Electronic USB Load
The original Elektorized Sudoku Test & verify USB power performance

4 May & June 2020 www.elektormagazine.com


lektor
DESIGN SHARE SELL ELECTRONICS

Projects
6 Open-Network Weather Station Mk.2
Part 1: Introduction and hardware elements

18 Universal Triac Control Module


with ATmega
Switch and dim a variety of loads

28 My IoT Button: A Button for the Web (2)


Part 2: Prototyping with board and cloud

38 BASIC for the ESP32/ESP8266 (2)


An hourglass with the ESP8266
and Annex WiFi RDS

Universal Triac Control 45 BalBot: a Self-Balancing Robot


Modern acceleration sensors ease the

Module with ATmega construction process

54 Tamper-Evident Box
Send data securely through postal services

18
62 Elektor New Precise Nixie Clock Revisited
An engineering bulletin for enthusiastic
users new and old

68 Practical ESP32 Multitasking (3)


Software timers

72 SigFox and the IoT (4)


Setting up a dashboard
Switch and dim a variety of loads 86 CAN Bus + Arduino
for Solar PV Cell Monitoring
Detect and locate serviceable panels in
large arrays

Next Edition
Elektor Magazine Edition 4/2020
(July & August)
A Wireless Temperature Sensor for the Nixie Bargraph
Thermometer • Home Information System • Advanced
LCR Meter Sneak Preview • Open-Network Weather Sta-
tion Mk.2 Software • S/PDIF Converter • Analogue Elec-
tronics Design (4) • HV Power supply with Curve Tracer
94 Inexpensive E-Scooter

108
• LED Booster for Microcontrollers • Home Automation
How does Lidl’s „road approved“ Made Easy • Node Red Book • Small Circuits & Tricks •
300-euro E-scooter perform? Retronics • and more.

101 Review: Elektor Magazine edition 4/2020 covering July & August 2020 is published
The PeakTech 6080 A Lab Power Supply around 3 July 2020. Delivery of printed copies to Elektor Gold Members is
A neat lab PSU for not much money subject to transport. Contents and article titles subject to change.

www.elektormagazine.com May & June 2020 5


LABS PROJECT

Open-Network
Weather Station Mk.2
Part 1: Introduction and hardware elements
By Mathias Claußen and Luc Lemmens (Elektor Labs)

In these times of climate change and global


concerns about the environment on everyone’s
lips, you too can make a positive contribution in the
form of building a powerful and extendable weather station,
not just for yourself and your ‘local log’ but also as part of
global, open networks like ThingSpeak and
openSenseMap. The station described in this
2-, possibly 3-installment article was designed
with flexibility in mind as far as measuring
and logging weather data is concerned, linked
to acceptable power consumption and high
reliability out there exposed to the elements.
The project revolves around an ESP32 module
connected to off the shelf sensors and running free
software with a lot of hooks for you to link to. Leaving little
to be desired except some sunshine and a light breeze!

Features Although its title includes “Mk.2” (mark-


2), this project is a fundamental redesign
• 3-PCB system: Main; Connector; Dust/Particle
of the ESP32 Weather Station [1], which is
• TH components and commercial modules
no longer recommended for new construc-
• Sensors (basic system): temperature, relative humidity, air pressure, dust/
tion. The PCBs for the present project
particulate matter
were designed to match the mechanical
• ESP32 based (Pico Kit)
parts of the weather station kit available
• I2C, I2C bus
in the Elektor Store, which includes an
• 12-V (solar) battery powered with automatic low voltage shutdown
installation rack and sensors for wind
• Screw terminal connectors for most wiring
speed, wind direction, rain, tempera-
• IP66-class cases for Main Board and Dust/Particle Board
ture, and relative humidity. In terms of
• Open-source software
hardware, the present project is split up
• Compatible with ThingSpeak, openSensemap
into three PCBs:
• Extendable with custom sensors
• RFM95 LoRa extension (optional, in development)
• Main board no. 191148-1 for install-
• ESPHome and Home Assistant compatible
ing outdoors in a waterproof case
• WiFi accessible
mounted relatively close to your
• SD card for local control
home.

6 May & June 2020 www.elektormagazine.com


• Connector board no. 191148-2 in the same case type as used for the
designed to fit into the case of a weather station’s main PCB. project decoder
thermo/hygro sensor, i.e. replacing These three boards will be discussed in sensors weather
the original internal hardware. It also this article, deferring the much larger
ESP32 ThingSpeak
provides RJ11 sockets for connecting part on the software to Part 2, possibly
openSenseMap
the wind and rain sensor modules. with a “stack overflow” to Part 3 once
The -1 and -2 boards are linked by the programmers start talking. entry level
7 wires in a conventional Ethernet
Æ intermediate level
cable (sporting 8 wires). Main board (no. 191148-1)
expert level
• Dust sensor board no. 191148-3, The main board contains a number
which is no more than an adapter of elements common to the sensors
board to alleviate connecting the employed in the weather station. The 3 hours approx.
Honeywell type HPMA115 dust sensor, elements are easily identified, even (PCB assembly only)
enabling it to be mounted remotely functionally, in the schematic in Figure 1.

lab tools, small drill

+5V
MOD1
DC-DC converter
T1 T2 OKI-78SR-5/1.5-W36-C €60 (main board incl. enclosure)
FQP27P06x FQP27P06x €40 (cone including BME280),
1 3 €50 (dust sensor incl. case )
GND
(prices approx.)
R2 R1 R9
2
100k

1M

C1
8
100µ 1k
25V
2
K1 IC1 LED 1
+ R3 R8 MAX8212
100k

1M8

-
4
Power supply with polarity
3
GND
protection and undervoltage
R4
5 lockout
220k

The weather station is normally


powered by a 12 V rechargeable battery
(-system), which gets its charge current
K8
from a solar panel combined with an
+5V
GND +3V3 +3V3 ANT1 +3V3 external solar charger. A maximum
current draw of 1.5 A is specified for
the weather station, heavily depending
K7
18 21 20 MOD3
RFM95
on type and number of sensors used. The
31 IO10
RX1 13 Elektor BOB
TX1
30 IO9 35 2
9
usable input voltage range is approxi-
MISO1 16
IO19 D2
IO23
34 3
MOSI1 D1
15 mately 11–14 VDC.
K10
33 4
IO22
36
IO22
IO18
32 5
SCK1 D0
14
11
FET T1 and resistor R3 afford battery
37 IO5 NSS
IO21 5
IO21
SVN EN
23 6
RES 12 polarity protection, the MOSFET conduct-
SVN 7
4
SVP SVP
8
ing only if the battery terminals are
+5V MOD2 C2 1 10 K2
R5 R6 ESP32-Pico-Kit
26
10µ
16V +5V connected the right way around.
K6 T3
2k2
2k2

IO34 SPEED
BS170 IO37
24
DIR
If — for whatever reason — the charging
5V I2C 7
SDA IO26
IO38
25
RAIN process or the powering device fails to
SCL
GND IO27
10 GND
produce enough energy to compensate
9 K3
6
IO25
IO33
8 for the power inevitably dissipated by
IO32
T4 the weather station, the energy source
K4 BS170
SCL
must be disconnected to prevent deep
29
SDA RX0
TX0/IO17
28
+3V3 K5 discharging, which is a common source
+3V3
27
12
+3V3 of battery failure. For this task we
K9 IO12 MISO
R7
V+ 1k IO13
13
MOSI selected the good old programmable
15 11
IO2 IO14 SCK
IO2 16
IO4 IO15 14 CS0 voltage detector type ICL8212, which
IO4
17
IO0 19
IO0 GND
today equals its CMOS successor type
GND GND GND

22
MAX8212 from Maxim Integrated. With
only three external resistors for adjust-
ing thresholds/hysteresis and one exter-
nal p-channel MOSFET as a switching
device, the ’8212 does exactly what we
Figure 1: Schematic of the Main Board in the Open-Network Weather Station Mk.2 that’s compatible want: avoid any risk of deep discharge
with global sensorics platforms like ThingSpeak and openSenseMap. Note the bare-bones but of the battery.
perfectly working bidirectional 3.3-V/5-V, FET-based level shifters on the I2C bus. With the given values for R2, R8 and

www.elektormagazine.com May & June 2020 7


R4 we have an ‘undervoltage lockout’ Picokit module sports an internal 3.3 V
a which disconnects the battery when its regulator with its output bonded out to
terminal voltage drops below 10.5 V and pins 18 and 21 and furnishing a 3.3 V
connects it back in circuit again at a level supply rail for use by other elements on
exceeding 11.1 V. the main board.
A DC/DC converter (MOD1) steps the
12 V battery voltage down to the 5 V Brains & brawn from an ESP32
regulated supply voltage for the ‘real’ The ESP32 is a cheap yet powerful micro-
electronics, with LED1 acting as the controller with an enormous amount of
Power On indicator. Note that the ESP32 ready-to-run software snippets and other

b
component list

-
+

T1 T2
K1 LED1

R3 R1R8 C1
R2 MOD1
(C) Elektor
R9

R4 IC1 191148-1
K8
5V
e GND 5V
C2 K9
K2

TX1 GND speed


MOD2
RX1 R7 IO0 dir
K7 IO4 rain
ANT1
K3

T IO2
V+ GND
MOD3
SCL
K4
MISO

MOSI
GND

SCK

CS0
3V3

SDA

K5
R6
R5

Figure 2: The main board at various stages T4 T3


IO22
IO21
SVN
SVP

of completion: (a) unpopulated; (b) with


GND
SCL
SDA
5V

components populated and modules inserted; K10 K6


(c) with standoffs mounted; (d) with display
mounted; (e) with internal cables connected.

8 May & June 2020 www.elektormagazine.com


’soft’ building blocks available on the
web. It also has good properties as far as IC1
LP2950-33LPE3 +3V3
sensor interfacing is concerned. Here, a
+5V
drop-in ESP32 Picokit module (MOD2) is 1 3

used to control and read out the sensors, C1 GND C2


10µ 2 10µ
display information on the LCD, write +3V3
16V 16V

logged data on the SD card, and commu-


nicate with an (indoor) computer via WiFi R1 R2 K2
8
WIND
6

10k
10k
(or LoRa, once we have it implemented). K1 5 K3
4 3 MOD1
+5V
The main board also contains a Reset and SPEED
3
SDA
4
2 SCL BME280 BOB
DIR
a User button, plus a USB connection for 1
MOD2
flashing the weather station’s firmware. +3V3
SDA
SCL
R3 NC 1 7
K4
SD card RAIN +3V3

10k
6
K5 GND
For the micro-SD card connector (K5) we 5
4 +3V3
RAIN
3
opted for a small breakout board avail- GND 2
NC
AIR
1
able in the Elektor Store. It has a 100-mil PRESSURE
191148-027 KD
pitch pinheader that’s easily soldered and
connected to the main PCB. This BoB has
to be mounted perpendicular to the main
Figure 3: Schematic of the Connector Board for the rain and wind sensors. It also accommodates
board in order to access the card. You can
the pressure/humidity/temperature sensor module.
either replace the straight pinheader on
the BoB with an angled type or use pliers
and judiciously applied force to bend the
pins over 90 degrees. Be careful not to case specified in the Component List. Connector board (no. 191148-2)
damage this small board though. The lab prototype of the board is pictured Although this board also accommo-
in Figure 2. Note that the 3.81-mm dates the pressure/humidity/tempera-
I2C bus & LCD (0.15-inch) PCB terminal blocks can be ture sensor (module), its main function
The on-board I2C bus is used for commu- turned 180 degrees (i.e. with the connec- is to provide connectivity between the
nication with the LCD (on K6) and the air tions facing inwards) to create more ESP32 microcontroller and the peripheral
pressure/temperature/humidity sensors space in the housing for connecting the sensors. Refer to the circuit diagram in
(on K4), but it can also accommodate cables. An oddball solution indeed but Figure 3. This ‘circuitry’ replaces the
other I2C compatible sensors or devices totally workable. board inside the thermo/hygro unit that
you may want to add to the weather
station. Pull-up resistors R5 and R6 are
needed for this bus. However, if you
connect an I2C device on K4 that already
contains pull-ups on the bus connections,
component list
be sure to omit R5 and R6 or desolder/
cut these parts from the PCB. The LCD
module suggested for use here [2] does
have on-board pull-up resistors tied to its
5 V supply voltage. FETs T3 and T4 act
as bidirectional 3.3 V / 5 V level shifters
to match the ESP32 I/O pins, which are
not 5 V tolerant.

Not forgetting…
MOD3 accommodates an optional RFM95
breakout board (BoB) to cater for LoRa
 
connectivity. This is a future extension
and not supported yet in the current
software release.
Connectors K7 and K8 interface to a
Honeywell particle (dust) sensor. The
sensor is subject to damage and malfunc-
tion caused by frost, so we didn’t mount
it in the thermo/hygro sensor case which
requires installing in more open space.
The PCB designed for the main board is
a perfect fit for the Spelsberg IP66-class

www.elektormagazine.com May & June 2020 9


comes with the WH-SP-WS02 outdoor
kit, and slips perfectly inside the case.
The 3.3 V LDO (low dropout) regulator IC1
is the only active component on this PCB.
Apart from the three pull-up resistors R1,
R2, R3 for the switches in the rain and
wind sensors, the other parts are limited
to a bunch of connectors for the sensor
modules used in the weather station.
The RJ-11 sockets connect to the wind
sensor (K2) and the rain sensor (K4),
their position corresponding to the holes
in the ‘evacuated’ thermo/hygro unit and
the text on the case.
Position MOD2 is for further sensors and
user access to the I2C Bus in the cone.
Elektor’s popular BME280 breakout board
is again used as a 3-in-1 sensor module
covering temperature, relative humidity
and air pressure. The pin numbering on
the PCB for position MOD1 matches that
Figure 4: Finished Connector Board. Also on this PCB is the combined pressure/humidity/
on the BME280 BoB. Should you prefer to
temperature sensor module.
apply a different brand of I2C compatible
T/RH/P sensor module, you can connect
it to position MOD2 and simply remove
the BME280 BoB from the PCB.
Figure 4 shows the connector board as
fabricated and tested by Elektor labs.
Note that the four holes permit securing
4 sale @ www.elektor.com the connection cable to the board with
two tie-wraps.
ªMain Board, bare PCB
www.elektor.com/191148-1
Dust sensor board (no.
ªConnector Board, bare PCB
www.elektor.com/191148-2
191148-3)
The main purpose of this board is to
ªDust/Particle Sensor Board, bare PCB
provide easy connection and mount-
www.elektor.com/191148-3
ing of the Honeywell HPMA115S0-xxx
ªWeather Station Mk. II, kit of parts
dust/particulate matter sensor module.
www.elektor.com/191148-71
Refer to the schematic in Figure 5. The
ª2×16 character LCD with I2C Backpack* Honeywell sensor has an 8-way, 1.25-mm
www.elektor.com/two-wire-lcd-071035-93
pitch (0.05 in.) connector that’s trouble-
ªWireless Outdoor Unit for Professional Weather Station WH-SP-WS02 some to connect without professional
www.elektor.com/professional-outdoor-weather-station-wh-sp-ws02
tools. The sensor is better manageable
ªMicro SD-Board BoB* if you use the Würth Elektronik connec-
www.elektor.com/19251 tor described in the Component List. Just
ªBME280 breakout board, I²C version (160109-91) solder the four wires to K3 (two for 5 V
www.elektor.com/bme280-mouser-intel-i2c-version-160109-91 power supply, and two for RxD and TxD)
ªESP32-PICO-Kit V4 and carefully plug the 1.25-mm pitched
www.elektor.com/esp32-pico-kit-v4 connector into the sensor. Connectors K1
 
and K2 then provide an easily managed
* Stock/shipping delays due to production and export issues.
and user-friendly connection between
the dust sensor and the main board.

Web Links
[1] ESP32 Weather Station, Elektor Labs magazine edition 1/2019: www.elektormagazine.com/magazine/elektor-70/42351
[2] 2×16 character LCD with I2C: www.elektor.com/two-wire-lcd-071035-93
[3] Publication support page: www.elektormagazine.com/191148-01
[4] Project development page: www.elektormagazine.com/labs/remake-elektor-weather-station

10 May & June 2020 www.elektormagazine.com


Figure 6 shows the completed board
+5V
with the sensor connected.
Use three M2 x 10 mm machine screws K3 K1
to attach the sensor to the PCB. Sure Dust sensor
Tx Tx
Rx Rx
enough you’ll need to drill a couple of Honeywell
HPMA 115SO GND K2
ventilation holes in the case to yield suffi- +5V GND
+5V
cient airflow for correct measurements,
yet prevent moisture to remain in the 191148-025-94 KD

sensor once it is installed out in the open.


Figure 5: Schematic of the Dust/Particle Sensor board accommodating the Honeywell HPMA115
Products sensor.
The three unpopulated circuit boards
for the Open-Network Weather Station
Mk.2, as well as a kit of parts, are avail-
able from the Elektor Store — see the
4 Sale @ www.elektor.com textbox.
Elektor Members preferring to order their
boards from a PCB manufacturer can do
so using the Gerber files and BOM files
available at [3].

Next time
In Elektor magazine edition 4/2020 cover-
ing the pleasant-weather months of July
& August we continue with the software
developed for the Open-Network Weather
Station Mk.2. You can actively follow the
progress on our Labs website [4].
191148-01

Figure 6: Ready assembled Dust/Particle Sensor Board mounted in the IP66 class case.

component list

www.elektormagazine.com May & June 2020 11


aI
Artificial Intelligence
for Beginners (1)
Object recognition using the Maixduino board
By Walter Trojan (Germany)

There is no hotter topic in the world of IT than artificial intelligence (AI). A good low-cost introduction to
the fields of speech and image recognition as well as other aspects of AI is the Maixduino board which,
including the fitted camera and small LCD panel, comes in at only around €30/£25/$35; what’s more, it can
readily be programmed using the familiar Arduino IDE. In the first instalment of this series we will look at
the comprehensive array of hardware offered by the Maixduino and at a couple of demonstration programs,
including one that can recognize 1000 different objects.

ing’, where more complex and optimized


program structures are used to improve
results further. We will be looking at
these ideas in more detail later in this
short series of articles.
However, AI is not a new subject: its
beginnings can be traced back to the
1950s. The breakthrough that occurred
a few years ago was the result of consid-
erable increases in the amount of compu-
tational power available. Graphics cards
with hundreds of processor cores operat-
ing in parallel and highly-specialized AI
chips enabled AI systems to be imple-
mented and trained. That opened the
door to automatic speech recognition,
as used in many personal assistants,
and image recognition of objects of all
kinds. AI also plays an important role
Figure 1: The hardware facilities offered by the Maixduino. in autonomous vehicles. In some areas
AI has already surpassed human abili-
ties: AI systems can beat world champi-
ons in the games of chess and go, and
The use of artificial intelligence is on the applications that it opens up. And last can detect tumours more reliably than
increase in many areas, and it is finding but not least, it’s a lot of fun! human medical specialists. But do not
its way into many types of device and The term ‘artificial intelligence’ is gener- worry: the systems are only superior in
application. This year it is estimated ally considered to cover the creation of the particular areas in which they have
that worldwide business applications in systems exhibiting intelligent behaviour. been trained, and the areas in which the
the field of AI will generate revenues of One part of this is ‘machine learning’, systems are trained will continue to be
some $4.8bn, and that figure is predicted whereby instead of having an application chosen by humans.
to rise to over $30bn by 2025. Anyone function specified in all its detail by the
with knowledge of the subject area can developer, a general-purpose program- A low-cost introduction
look forward to enhanced employment ming framework in the form of a neural A good low-cost introduction to this world
prospects as expertise in AI is urgently network (NN) is used, which learns the is the Maixduino, which in the form of the
sought after. It is therefore worthwhile required function by itself using a large ‘MAix BiT’ kit including the board, camera
to take a little time to get to grips with corpus of training data. One class of and small LCD panel can be obtained
the topic and the new worlds of possible machine learning is called ‘deep learn- from Elektor: see the text box. The board

12 May & June 2020 www.elektormagazine.com


Figure 2: Maixduino pinout.

has the same format as an Arduino Uno notice the higher component density and an audio amplifier with a 3 W output
(from which it gets its name), but the that many additional connections are driven by a digital-to-analogue converter.
hardware it includes is considerably more available. At the heart of the board there So there is plenty of hardware on the
comprehensive. The board is manufac- are two large modules. The first is the board to let you get started on a range
tured by the Chinese company Sipeed. Sipeed M1 AI processor module based on of possible projects without having to
Alternatives to the Maixduino include the the Kendryte K210 device, whose interior add extra boards.
Nvidia Jetson Nano, the ROCK PI N10 workings we will look at later, and the The pinout of the board (see Figure 2)
Model A, the Intel Neural Compute second is an ESP32 module for communi- closely resembles the original. The
Stick 2 and others, but these all cost cating over WLAN and Bluetooth and for supply voltage can be provided over
considerably more. acquiring analogue signals. The ESP32 the DC barrel jack or using the VIN pin
In this first instalment of this series we contains two processor cores clocked at at 6 V to 12 V; alternatively, 5 V can
will look at the rich hardware environ- 240 MHz and so by itself offers a consid- be supplied over the USB connector. Six
ment offered by the Maixduino and how erable amount of processing power, and of the ESP32’s GPIOs are brought out;
it can be programmed with the help of it can be used to offload communica- these are the ones that can alternatively
the Arduino IDE. As well as a couple of tion functions from the main processors. be used as analogue inputs A0 to A5. On
typical Arduino-esque applications we will The ESP32 has already featured in many the opposite edge of the board are the
look at how to use the camera and the articles in this magazine, and so we will inputs and outputs of the K210 module.
screen. And the final highlight will be a not go into further detail about it here. These can be controlled using the usual
demonstration of how to use the board The header connectors correspond in Arduino commands, with the ‘Arduino pin
to recognize objects. number and arrangement to the origi- number’ being the number of the input
In the second and third instalments we nal Arduino, and the pin assignments or output bit of the K210.
will delve deeper into the topic of artifi- are mostly identical. But beware that  
cial intelligence, describe the structure of the inputs and outputs are designed for #define LED 12
neural networks, install MicroPython and 3.3 V or even 1.8 V operation, and the // K210 IO12, Maixduino pin 10
its accompanying IDE and demonstrate input circuitry will be destroyed if pinMode(LED, OUTPUT);
how facial recognition works. We will also 5 V is applied. // configure port as output
look at how you can program your own Further details are shown in Figure 1.
digitalWrite(LED, HIGH);
AI applications and how to communicate Two 24-pin sockets are provided for
// port to high (3.3 V)
with the Internet. interfacing to the camera and to the LCD  
panel. A slot is provided for a microSD The RST pin is designed to operate at
A deep dive into the ‘super card which can be used to make a 1.8 V and external circuitry should not
Arduino’ large amount of storage available to apply a higher voltage than that to it.
The specifications of the Maixduino will the Maixduino. The USB connector is Outputs IO36 to IO47 are also designed
have hardware enthusiasts licking their the modern type-C kind and is used for for low-voltage operation: these are not
lips! The overall size and construction of programming and monitoring. And, to brought out to the headers, but are used
the board is broadly aligned with that of allow the processing of audio data, the internally, for example to drive the LCD
the Arduino Uno, but you will immediately board includes a digital microphone and panel. The serial RX and TX ports and the

www.elektormagazine.com May & June 2020 13


The big enchilada: price point: 0.46 Tops, or 460 billion
Kendryte K210 operations per second. With overclock-
The K210 SoC (system on a chip) made ing this figure can even be doubled,
by the Chinese company Kendryte is at allowing, for example, up to 60 objects
the heart of the Maixduino. It is made per second to be recognized. The high
using a low-power silicon technology on processing performance is achieved using
a 28 nm process and has been avail- 64 arithmetic units operating in parallel
able on the market since September and a bus width of 576 bits. Also, the
2018. For carrying out ‘normal’ work it power dissipation of just 0.3 W is very
offers two 64-bit processor cores that are low in comparison to other AI systems.
clocked at 400 MHz, with overclocking For example, Nvidia recommends using
up to 800 MHz possible. These cores are a 5 V 4 A (hence 20 W) power supply for
based on the RISC-V specification: this its Jetson Nano, which at 0.4 Tops offers
saves the manufacturer from having to comparable computing power.
Figure 3: Block diagram of the Kendryte K210. pay licensing fees to Arm and so helps The KPU can implement advanced neural
to contribute to the low total cost of the network architectures, including convo-
device. Both processors come with an lutional networks. These have a particu-
FPU (floating-point unit) that operates larly efficient filter structure that makes
I2C interface are provided with suitable in both single and double precision. them especially well suited to image
pull-up resistors fitted on the board. Figure 3 shows in more detail what is processing applications: more on this in
Unfortunately the K210 datasheet does inside this chip. the second instalment of this series. The
not specify the maximum output current The special feature of the K210, however, main memory included in the SoC has a
available at the outputs. However, they is its KPU (knowledge processing unit) capacity of 8 MB, divided into 2 MB for
should be capable of driving an LED at up that can be used to construct and execute the main processors and 6 MB for the
to say 10 mA or so; for higher currents neural networks. The total compute KPU. That means that up to 5.9 MB is
a driver IC should be added. power available is astonishing at this available for storing the neural network
configuration, which is enough to imple-
ment a medium-sized network.
 
However, the K210 has more hardware
tricks up its sleeve. These include an
audio processing unit (APU) which is
particularly helpful for pre-processing
in speech recognition applications. The
unit can handle up to 8 channels (or 4
stereo channels) at input sample rates
of up to 192 kHz. An FFT (fast Fourier
transform) unit is available to carry out
analysis of the frequency spectrum of
a signal.
Also noteworthy are the AES and
SHA-256 accelerators provided to speed
up cryptographic functions.
And of course the device includes the
usual complement of peripherals includ-
ing UART, I2C, SPI, I2S, timer, RTC and
Figure 4: Adding the Maixduino core configuration. PWM.
Sipeed has added 16 MB of flash memory
on the board alongside power supply
circuitry, the microphone and 3 W
power amplifier, and the excellent ESP32
module.
What more could you wish for? More
information on the operation of the
board, the circuit diagram and other
details can be found by following links
[1], [2] and [3].

Software development
It is not just the shape of the board
Figure 5: Installation of the Maixduino core tools. that is similar to the original Arduino:

14 May & June 2020 www.elektormagazine.com


the board uses the same Arduino IDE,
with the Maixduino core being integrated
into the environment in the same way
as the ESP8266 or ESP32. Under File ->
Preferences it is necessary to add a new
board manager URL: if you right-click on
the button to the right of the text entry
box a small window will open to make
entering the URL easier (see Figure 4).
If you only want to program the Maixdu-
ino, then only the ‘sipeed’ line needs to
be added; then the on-board ESP32 will
also be programmed using it.
To install the Maixduino board tools select
the menu item Tools -> Board -> Boards
Manager. Enter the search term ‘Maix’
(as shown in Figure 5) and then proceed
to install the tools.
Now we can start to do some program-
ming. Rather than the conventional ‘hello
world’ program, we will jump straight
into to testing the camera and screen.
Connect the Maixduino over USB and
in the Tools menu set the following
parameters.
 
Board: Sipeed Maixduino
CPU Clock Frequency: 400 MHz
Figure 6: Arduino IDE with the ‘selfie’ program.
Burn Tool Firmware: open-ec
Burn Baud Rate: 1.5 Mbps
Tool Install Location: Standard
Port: <COM port that you are using>
Programmer: k-flash
 
A demonstration program that captures
an image and displays it on the LCD is
already available within the IDE. Call it
up using File Examples Sipeed_OV2640
selfie and once it is uploaded to the board
(you may need to press the reset button
at this point) you can run it. The code is Figure 7: Captured image of an adaptor plug.
shown in Figure 6.
The program starts by bringing in the
functions from the Sipeed libraries for
driving the camera and LCD, which are Our first AI model suming, it is not really practical to carry
connected to the board using an SPI bus. We will be looking in more detail at deep it out on the Maixduino. However, it is
The image format chosen is QVGA resolu- learning aspects of artificial intelligence possible to install a ready-trained model
tion (320 by 240 pixels) with RGB565 in the second article in this series, but and immediately set it to work recog-
colour. The setup routine initializes both here we can demonstrate a simple appli- nizing images. The steps to achieve this
devices, and in the main infinite loop the cation. We will be using ‘MobileNet’: are as follows.
captured images are transferred directly nothing to do with mobile phones, but  
to the LCD: it could hardly be simpler. rather an image classifier that can recog- The required software can be found
The image is not particularly contrasty, nize and identify 1000 types of every- at link [4]. It consists of the following
but it is sharp and updates are smooth. day objects. This uses a neural network, components.
Figure 7 shows the results. which is a software structure built from  
As you can see, the Maixduino is as easy nodes organized in layers trained using • mobilnet_v1.ino: main C++
to use as an Arduino Uno. However it a lengthy process in which it is presented program for running the
offers many more possibilities and we can with thousands of images. demonstration
immediately start to build more sophis- Since the file containing the training • MBNet_1000.h: header file for the
ticated applications. image set runs to some 200 GB and the demonstration routines
training process itself is very time-con- • MBNet_1000.cpp: C++ routines for

www.elektormagazine.com May & June 2020 15


libraries available. The first part of the
program declares the camera, LCD and
the KPU along with their parameters. The
camera resolution is configured to the
same format as the training images, 224
by 224 pixels. Finally, the object mbnet
marshals together the KPU, camera and
LCD resources.
The setup routine initializes the demon-
stration code, and then in the main
loop we have the classification of the
objects in the images acquired by the
camera and their display on the LCD
panel. Again, it is hard to imagine that
an object recognition program could be
any simpler.
 
As a test we can put a photograph of
a cat in front of the camera (as shown
in Figure 9). The system immediately
recognizes it as a tabby or Egyptian cat
(Figure 10). The application is capable of
classifying about five images per second
and is therefore capable of producing
useful results even if the camera is
moving. The most important things are
to have good lighting and not too busy
a background to the image.
Figure 8: MobileNet demonstration program.
As can be seen from Figure 10 the
acquired image uses only a blue and
white colour palette, in the interests of
acquiring, recognizing and displaying find a folder mobilenet_0x300000 in increasing the recognition rate. This is
objects which there are two files: the model is a commonly-used method: instead of
• names.h: header file with object the one called ‘m’. Copy this file onto using all three colour channels in an
descriptions a microSD card in the root (top-level) image we use only one to reduce the
• names.cpp: C++ routine for describ- directory and insert the card into the amount of pixel data and hence the
ing the recognized objects slot on the Maixduino. amount of processing power required.
    The technique of using a ready-trained
Download these files and place them all A glance at the program code in Figure 8 network, or in other words of carrying
in the same directory. The pre-trained AI shows that it is possible to program out training and classification on different
model mobilenet_0x300000.kfpkg can be even very complex applications with platforms, is also widespread in this type
downloaded from link [5]: compressed, little effort. That is of course all down of application. Many users take advan-
it is just a few megabytes long. After to the powerful libraries: in the field of tage of the large amounts of processing
decompressing it with 7zip you should AI there are very many highly efficient power available on AWS, Microsoft Azure

Figure 9: Acquisition of an image of an object.

16 May & June 2020 www.elektormagazine.com


or Google Cloud to train their neural
networks, while running them (which 4 sale @ elektor.com
requires considerably less in the way of
ªSipeed MAix BiT Kit for RISC-V AI+IoT
resources) on smaller-scale platforms.
www.elektor.com/sipeed-maix-bit-kit-for-risc-v-ai-iot
The semiconductor industry is already
responding to this demand: Intel recently
announced their Nervana NNP-T and
NNP-I neural network processors, where
the ‘T’ version offers higher processing application and at how to develop your the book Make Your Own Neural Network
power for training, and the ‘I’ version own neural network structures. If you are by Tariq Rashid is recommended.
is a lower-performance device aimed at too impatient or curious to wait for that, 200023-02
inference and classification applications.

Coming up...
The demonstration application we have
looked at in this article can only scratch
the surface of the topic of artificial intel-
ligence, but with luck your interest in the
possibilities of machines that learn has
been piqued.

In the next instalment of this series we


will look at the structure and function
of a neural network in more detail.
That will come with a new development
environment: we will be introduced to
the temptations of Linux and the Python
programming language, as that is where
the most powerful libraries and frame-
works are available. These frameworks
make the creation of a neural network as
easy as plugging together Lego bricks.
We will also look at a face recognition Figure 10: The object is identified and classified.

Web Links
[1] Maixduino description: https://wiki.sipeed.com/en/maix/board/maixduino.html
[2] Sipeed forum: https://bbs.sipeed.com/
[3] Maixduino circuit diagram: http://dl.sipeed.com/MAIX/HDK/Maixduino/Maixduino-4.30/
[4] MobileNet demonstration: https://github.com/sipeed/Maixduino/tree/master/libraries/Maix_KPU/examples/mobilenet_v1
[5] MobileNet model data file: http://dl.sipeed.com/MAIX/MaixPy/model/mobilenet_0x300000.kfpkg

Advertisement

Hand held enclosures


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

01256 812812
[email protected]

www.elektormagazine.com May & June 2020 17


HOMELAB PROJECT

Universal Triac Control Module


with ATmega
Switch and dim a variety of loads
By Roland Stiglmayr (Germany) This triac control module is a project for everyone interested in
power electronics. It also gives you an opportunity to learn a
bit about hardware-level programming. We describe all the
wonderful features of triacs and their applications, as
well as how you can employ rarely used resources
of the microcontroller.

Everyone involved in electronics knows more or less what module. Figure 1 shows the author’s finished prototype. Many
thyristors and triacs are, how they work and how they are functions are possible with this combination of an ATmega
used. However, these components offer so many possibilities microcontroller and a triac. Depending on the firmware, the
that only specialists are able to fully exploit their potential. module can be used as a simple switch or remote switch, a
Nowadays thyristors are mainly used in special applications timer, a dimmer, or a soft-start module for switching inductive
with high voltages (above 1 kV) and strong currents (many loads such as transformers or motors.
kiloampères), so this article only focuses on triacs.
  Basics
First we look at the basic operation of triacs and the relevant A triac is a semiconductor switch that conducts current in both
parameters. Then we describe the circuitry of the control directions when it is switched on, which means it is an AC

18 May & June 2020 www.elektormagazine.com


switch. The load current flows through the two electrodes T1
and T2 (here ‘T’ stands for ‘terminal’). These electrodes are
also designated MT1 and MT2 (for ‘main terminal’), and in the
past they were also called A1 and A2 (for ‘anode’). The third
electrode is the gate (G), which is the control lead. Figure 2
shows the Elektor circuit diagram symbol for a triac (on the
left) and a simple equivalent circuit (on the right).
A triac remains in the off state until the current flowing from the
gate (G) to T1 is high enough to switch it on. Once the triac is
switched on, it remains in the on state until the current between
T1 and T2 drops below a threshold value, which depends on Figure 1: The author’s prototype of the control module.
the type. Then it returns to the off state. In operation with an
AC voltage, this means it switches off at every zero crossing of
the current, which is not necessarily in phase with the voltage,
unless it is constantly kept on by the gate current. Accordingly,
a triac can be triggered by a short, low-energy pulse on the
gate, but it cannot be directly forced to switch off.
T1 is the reference point (reference voltage) for the gate G.
There are four different directions of current flow, depending on
the polarity of the voltages on the gate and T2 relative to T1.
These are shown by the four-quadrant diagram in Figure 3.
The X axis represents the polarity of the voltage on the gate
relative to T1. The Y axis represents the polarity of the voltage
on T2 relative to T1. The resulting four quadrants are labelled
with Roman numbers in Figure 3. Positive values are shown in
red, and negative values in blue. On the data sheets, the triac
parameters are stated for all four quadrants because they are
often different.
Figure 2: Elektor schematic symbol Figure 3: The four quadrants
Parameters for a triac (left) and an equivalent result from the polarities of the
To trigger a triac into conduction, the gate current must be circuit for the first quadrant, voltages on the gate and T2
higher than the threshold value, which is designated as the gate composed of PNP and NPN relative to T1.
transistors (right).
trigger current IGT. At the end of the control pulse, the triac only
stays on if the resulting load current is higher than the latch-
ing current IL. Otherwise the triac switches off after the end of
the control pulse. The trigger currents and other currents are it is exceeded, the triac will fail with a short between T2 and
specified for each quadrant separately on the data sheets. If T1. This results from non-uniform current density around the
the load current through a switched-on triac drops below the gate electrode, leading to local overheating. As the value for
holding current IH, the triac switches off again. dIT/dt is especially low in the fourth quadrant, this operating
With an inductive load there is phase shift between the current mode should be avoided. The dIT/dt issue is relatively minor if
and the voltage, with the amount of the shift depending on the switching occurs at the voltage zero crossing, although this is
inductive component of the load. Consequently, the voltage only true for predominantly resistive loads. If necessary, the
on the load is not necessarily zero at the zero crossing of the rate of rise of the current can also be limited by connecting a
current. As a result, the voltage on T2 can jump to a high value small air-core choke ahead of the triac.
when the triac switches off. This can cause problems. If the The parameter dICOM/dt defines the limit value for the rate of rise
voltage rate of rise is higher than the limit value dVCOM/dt, the of the current at the zero crossing of the current. If this value is
triac will be switched on again. Depending on the load, this can exceeded, the triac will not switch off but instead remains on.
be damaging. An excessive rate of rise can be prevented by The triac can also be triggered falsely if the repetitive peak
connecting a RC network called a snubber across T1 and T2. off-state voltage VDRM is exceeded. This can be remedied by
There are also ‘Hi-Com’ triacs available that are significantly connecting a varistor between T2 and T1 to limit the maximum
less sensitive in this regard. voltage.
The dVD/dt parameter is also relevant. If the limit value of
this parameter is exceeded on a triac in the off state, it will The last parameter that needs to be explained is the overcur-
also switch on. If the resulting current flows for exactly one rent protection factor I²t, which is the integral of the square
half-wave, a transformer switched on this way can enter satura- of the current over a 10 ms period. This limit corresponds to
tion and suddenly present a low impedance. In many cases the maximum energy absorption of the triac. It must always
the triac, and possibly the tracks on the PCB, will not survive be taken into account in the dimensioning of the fuse.
such an incident. Here again, a snubber or a Hi-Com triac can All other quantities listed on the triac data sheet are largely
remedy the situation. self-explanatory. If you want to design your own triac circuits,
The parameter dIT/dt, which is the limit value for the maximum you should now be able to use these parameters to select the
current rate of rise after triggering the triac, is also critical. If best triac for your application.

www.elektormagazine.com May & June 2020 19


R11 R12 R13
AC_N D13
KL2-1 15k 15k 15k
SM4007 R19 R20 R21
AC_N
KL2-2 100k 100k 100k
C7 47n
250V AC D14
SM4007
R25 R26 R27
LOAD
KL1-1 4k7 22k 22k
R22
R16 R17
R24

100k
220 120

1k
SCR1
C8 BTA_312B R15
CX1

4k7
47n C6
D5
235V AC 4,7n 10n
LL4448
AC_L 250V AC
KL1-2

F1
T4A
ATMEGA168PA_TQFP
R4
29 23
22k PC6(/RESET) PC0(ADC0)
24 JP2
PC1(ADC1) 1 2
21 25
GND PC2(ADC2) 3 4
26
20 PC3(ADC3) 5 6
AREF 27
18 PC4(ADC4/SDA)
28 ISP
AVCC PC5(ADC5/SCL)
19 R10 R9 R2
ADC6
C2 22

100k

100k
ADC7

22k
22p 7
PB6(XTAL1/TOSC1)
3 30
4 PD0(RXD)
31
PD1(TXD)
2 X1 32
PD2(INT0) OK2
C3 1
1 8 PD2(INT1) LTV816S 1 R7
22p 2
PB7(XTAL2/TOSC2)

470
PD4(XCJ/T0) 4
9
3 PD5(T1) S2
GND 10
PD6(AIN0) JP1
5 11 3
GND PD7(AIN1) 1 3
4 1
2 D2 LL4448
VCC 12 2
6 PB0(ICP) 2 4 2 D1 LL4448
VCC 13 4 3
PB1(OC1A)
14
PB2(SS/OC1B)
15
PB3(MOSI/OC2) 3 R8
16

470
PB4(MISO) S1
17 R5 R3 OK1 1
PB5(SCK)

100k
470
LTV816S
1 3
IC1
D10 C1 C5
2 4
5V2 220µ 100n
LED1 C4
470p

190047-006-94 KD

Figure 4: The circuit diagram of the control module. Crystal X1 has a frequency of 11.0592 MHz.

Triac control module A series capacitor would be simpler, but MKT capacitors with
Now let’s get down to practice. Thanks to its intelligence, the the necessary capacitance and voltage rating are not exactly
universal triac control module can act as a multi-purpose simple cheap. A series resistor is even simpler. We want the triac to
switch, a timer with delayed switch-off or a dimmer, or be used operate in quadrants II and III. This requires a negative gate
to control inductive loads. That’s a lot of versatility from a trigger voltage relative to the T1 electrode, which is connected
single module. If you understood ‘intelligence’ to mean ‘micro- directly to the AC mains. This is most easily achieved with a
controller’, you got it right. Here we chose an ATmega device. half-wave rectifier. However, the feasibility of this is directly
With regard to triac selection, the main criteria are the current dependent on the current consumption of the circuit.
to be switched and the maximum voltage on the triac. With The MCU and the trigger energy required by the triac are the
operation from a single-phase AC mains, around 600 V is main considerations in this regard. The MCU does not have much
sufficient (230 V × √2 plus a safety margin). For industrial to do and can therefore spend most of its time in low-power
applications it is better to use triacs with 800 V reverse sleep mode. The average trigger energy is low because only
voltage rating, due to the high transient voltages in indus- short trigger pulses are needed. The question is how low we
trial environments. The current actually possible in practice can make the current consumption. The MCU is in Extended
depends not only on the rating of the triac, but also on the Standby Sleep Mode most of the time and is only awakened
manageable power dissipation, and thus on the cooling. to generate the trigger pulses.
The power dissipation is equal to the product of the forward  
voltage and the switched current. The worst case is high-frequency triggering without zero cross-
The minimum load current in the application must also be ing detection, with a trigger signal generated every 278 µs.
considered. Both IL and IH must be clearly exceeded, as other- Then the ATmega needs 1.9 mA in practice, with a V CC of
wise the load will not be switched on cleanly or the current will 4.7 V. With a peak gate current of 11 mA for each 10 µs pulse
not flow continuously. The 600 V devices BT134-600E (4 A) and a period of 278 µs (3.6 kHz), the average gate current is
and BTA312B (12 A) are good general-purpose devices that 400 µA. The total current is therefore approximately 2.3 mA.
are suitable for many simple purposes. This determines the value of the series resistor and its power
dissipation. With half-wave rectification, the effective value is
Powering the module Ipk/2 and the average value is Ipk/π. This yields:
Supplying power to the module is not trivial. A small switching
power supply would be nice, but would need a lot of space. Ipk = 2.3 mA × π = 7.3 mA

20 May & June 2020 www.elektormagazine.com


R = 325 V / 7.3 mA = 45 kΩ

Ieff = Ipk / 2 = 3.7 mA

The power dissipation of the resistor R is:

Pdis = Ieff² × R = (3.7 mA)² × 45 kΩ = 0.62 W


 
If R is divided into three individual 1 W resistors, then the power
dissipation and the applied voltage do not present any problem.
There is also an issue with switch-on. As long as the MCU is
in reset mode, it draws a relative large current and VCC rises
only very slowly. This can be solved by setting the BOD level
to 2.7 V and immediately activating sleep mode for 250 ms.
This is explained later on. Figure 5: How to set the fuses when you program the ATmega the first
time.
Safety
You should never ignore the danger of a module operating
directly from the AC mains. With AC mains operation, you
shouldn’t connect any measuring instruments, and definitely
not a PC. Things like this should be left to qualified electricians,
and isolation transformers and other equipment are mandatory.
Be sure the module is protected against touch contact when
it is connected to the AC mains. It should always be fitted in
an insulating case.

For tests or modifications, the module must be completely


separated from the AC mains and powered from a 5 V supply.
A 50 Hz signal with an amplitude of 4 V from a square-wave
generator, injected at C4, can be used as a test signal for zero Figure 6: Settings for flashing the firmware with an ISP programmer.
crossing detection.

Hardware
In the circuit diagram shown in Figure 4, power for the MCU
and the peripherals is provided by the series resistors R11-R13, (IC1) is programmed through the ISP interface on JP2. Fuse
half-wave rectification with D13, and filtering with C1. The MELF F1 at the AC mains input protects the circuit in the event of
resistors used here for R11-R13 have a high breakdown voltage a short circuit.
and power rating. Due to the high impedance of the power
supply, it effectively approximates a current source, allowing Software
the Zener diode D10 to easily provide a constant voltage. The project software [1] was written using the Arduino IDE.
The MCU clock is controlled by crystal X1 to ensure precise However, the author did not use the Arduino functions because
timing of the trigger pulses. The network formed by diode they are too slow. The program created by the author is very
D12 and the voltage divider R2, R3 and R19-R22 generates fast and operates in real time. The sketches were there there-
a signal suitable for zero crossing detection, which is clipped fore intentionally not ported to Atmel Studio.
to VCC by diode D5. Unfortunately, it is not possible to use the boot loader to
The gate current is limited by R16 and R17. Fast triggering program the microcontroller. So much current would be needed
of the triac is provided by C6 in parallel with R16. A snubber at switch-on that the supply voltage would not rise. This means
formed by R24 and C8 is connected across T2 and T1 of the that the fuses must be set to disable the boot loader. The
triac to prevent false triggering. The triac used here is a Hi-Com microcontroller can be programmed directly from Atmel Studio
type, so the combination of a small capacitance and relatively using a suitable ISP programmer.
high resistance is sufficient. For each app, the project folder contains the corresponding
sketch and the hex file. In the initial programming, it is essential
The optional auxiliary load, consisting of R25-R27 and C7, is to program the fuses as shown in Figure 5. Then the desired
a special feature. It is only required if the external load has hex file can be loaded from the project folder and flashed in
high inductance, such as a transformer. These components are the MCU (see Figure 6). If a sketch is modified, it must be
usually not fitted. Capacitor CX1 suppresses RFI. recompiled (verify and compile). The IDE status field shows
The module is operated using the pushbutton switches S1 the folder containing the generated hex file. An example of a
and S2. This can also be done with optocouplers OK1 and typical file path is
OK2 connected in parallel with the switches. Switches with
long actuator pins should be used to ensure adequate safety C:\Users\name\AppData\Local\Temp\buildxyz.tmp/
distances. LED1 acts as a power indicator. The microcontroller Triac_...ino.hex

www.elektormagazine.com May & June 2020 21


Figure 7: Relationships during switch-on. Ch1 (blue): gate pulses; Ch2 Figure 8: Voltage on the triac with uncorrelated trigger pulses over a
(green): current; Ch4 (red): VCC. X1, Y1: Start of WDT and sleep mode, period of 1 s. Top trace (Ch2): mains zero crossing; middle trace (Ch1):
BOD level 2.7 V; X2: WDT timeout, wake-up. gate pulses; bottom trace (Ch4): voltage on triac.

  Applications
As the folder name and build number are reassigned every All apps have the same initialisation procedure. On power-up,
day, the file also has to be updated daily in Atmel Studio. If
the BOD level of 2.7 V determines the end of the reset inter-
the folder AppData is not visible in File Explorer, select Show
val. After the following program start, the watchdog timer is
hidden files and folders under View/Options. activated and the program is put into sleep mode. This allows
Then load the desired hex file in Atmel Studio and program VCC to rise quickly and reliably (Figure 7). The WD timeout
the ATmega microcontroller. triggers the WD interrupt and terminates sleep mode. Then
execution of the actual program starts.
Warning: For programming, the module must be fully separated The sketch excerpt in Listing 1 shows how setting the WD
from the AC mains and powered by a safe low-voltage supply. timer and sleep mode is implemented. The listing contains part
of the code of the initialisation procedure. First the watchdog
is set and activated. Then the microcontrol-
ler is put into sleep mode. The WD timeout
triggers the WD interrupt, which wakes up the
Listing 1
microcontroller.
void setup()  A separate sketch is available for each example
{ app. Each app has its own distinct functions,
 //after reset, start with sleep mode to stabilize VCC. which can be selected using pushbuttons or
 //prepare the watchdog for wakeup
jumpers. More information is available in the
comments of the individual sketches.
 
   asm ("WDR");             //clear wd-timer
A simple switch and timer app
   WDTCSR= 0x1c;            //set WDCE, WDE to enable setting 
The Sketch Triac_no_zd_32 app manages
   WDTCSR= 0x1c;            //wd-timer 0.25s       without zero crossing detection, so it illustrates
   WDTCSR= 0x14;            //clear WDE the basic programming of the module and its
   WDTCSR= (WDTCSR | 0x40); //set WDIE, enable WD-interrupt features. The module is operated from a 5 V AC
   interrupts();            //enable interrupts       power adapter for programming and testing. If
  you are interested in hardware-level program-
   SMCR= 0x0f;              //prepare xtd-standby ming of the WD timer, the various sleep modes,
   asm ("SLEEP");           //enter sleep mode the interrupts, the timer functions or the I/O
   SMCR= 0x00;              //finish, not necessary            commands, you should study the code in
   noInterrupts();          //disable interrupts, after wakeup
detail. All of the software can be downloaded
free of charge from the Elektor web page for
        
this article [1].
   MCUSR= (MCUSR & 0xf7);  //clear WDRF, wd-reset active
   WDTCSR= WDTCSR | 0x18;  //set WDCE, enable setting WDE
With this app the module can act as a switch
   WDTCSR= 00;             //clear WDIE, disables wd-timer or as a timer, with the actual function selected
  by a pushbutton. With the additional operat-
  ​
   . . . ing mode ‘Autostart’, the timer starts running
  immediately after power-up and the load is
} switched off when the timer period expires.
This function can be used to limit how long a

22 May & June 2020 www.elektormagazine.com


Figure 9: Switching on a LED lamp at the zero crossing of the mains Figure 10: Switching on a LED lamp at the voltage zero crossing.
voltage. Ch1 (blue): gate pulses; Ch2 (green): voltage on triac; Ch4 (red): Waveforms over 1 s. Ch1: gate pulses; Ch2: voltage on triac; Ch4: zero
zero crossing signal. crossing signal.

lamp remains on. The switch-off time is stored in the program. Dimmer
In the on state, the program generates periodic 10 µs pulses Dimming the brightness of a lamp is a typical application for
with an period of 278 µs to drive the triac. The control pulses a triac. The lamp power is adjusted by phase angle control.
are not referenced to the AC mains frequency, so the switch- Here the switch-on point of the load (phase angle) is varied
ing times are not synchronized to the mains voltage. In the with respect to the zero crossing point of each half-wave of
worst case, the load will only be switched on 278 µs after the mains voltage. Dimmers can cause a lot of EMC problems
the zero crossing. At this point the mains voltage will have because they generate voltage waveforms with high amplitudes
already reached 29 V, resulting in voltage spikes that can and steep edges, depending on the phase angle. The worst case
cause EMC problems. To illustrate this, the oscillogram in is switching at the crest of the mains voltage (with a phase
Figure 8 shows what happens over an interval of 1 second. angle of 90°). When the triac is triggered, the voltage on the
The trigger pulses are not correlated to the zero crossings, triac quickly drops from the crest value to zero (Figure 11).
so they wander with respect to them. The voltage over the Depending on the load, this results in very high currents and
triac varies according to the offset between the zero cross- high noise levels. An upstream RFI filter (for example, from a
ing and the trigger pulse. discarded dimmer) is therefore essential.
This is remedied in the next practically oriented application, in Many LED lamps do not work with conventional dimmers, due
which the zero crossings are detected so that triac triggering to the design of their power supply. This module also has diffi-
is synchronised with the zero crossings. Unlike the following culties with quite a few LED lamps. You should therefore use
measurements, the reference voltage here is VCC. T1 of the dimmable lamps.
triac is at VCC, so here you see the control pulses on the gate
with negative polarity. An interesting feature of this triac control is that after the
first pulse, additional pulses are inserted until the end of the
Switch and timer with zero crossing detection half-wave. This allows the module to be used with relatively
Unlike the previous app, here a signal derived from the AC complex loads. At full power, the first pulse after the zero
mains voltage is used to detect the zero crossings of the mains crossing is extended to 190 µs. This ensures that IH is exceeded
voltage. This signal is applied to the INT0 input, where its
falling edges trigger interrupts that mark the start of the first
half-wave. The end of this half-wave and the start of the next
half-wave are determined by Timer 2. This avoids complicated
hardware for precise detection of both zero crossings.
For reliable triggering with low load currents, the first trigger
pulse of each half-wave is extended to 280 µs. It is following by
two more 10 µs trigger pulses. This ensures that the IL of the
triac is exceeded even with high-impedance loads. Figure 9
shows this relationship. The short bumps (approximately 3 V)
in the voltage on the triac at the end of each half-wave are
particularly noteworthy. They result from the relatively low
current through the connected LED lamp, which drops below
IH at the end of each half-wave. However, this has little impact
on the noise level.
Figure 10 shows the superimposed traces over an interval
of 1 second. The control pulses are synchronous with the Figure 11: Dimmer with phase angle control. Ch1 (blue): gate pulses; Ch2
mains voltage. (green): zero crossing signal; Ch4 (red): voltage on triac.

www.elektormagazine.com May & June 2020 23


Figure 12: Control pulses after a restart. Ch1 (blue): gate pulses; Ch2 Figure 13: Control pulses in the settled state with expanded area below.
(green): zero crossing signal. The expanded area at the bottom shows the Ch1 (blue): gate pulses; Ch2 (green): zero crossing signal. Filler pulses
increase from five to seven pulses. are generated for 5 ms after each zero crossing.

Figure 14: Transformer current with no load. Ch1 (blue): gate pulses; Ch2 Figure 15: Transformer current with a small load. Ch1 (blue): gate pulses;
(green): zero crossing signal; Ch4 (red): transformer current. Ch2 (green): zero crossing signal; Ch4 (red): transformer current.

even with high-impedance loads. you should start with a phase angle of around 180° and then
The output power can be set with the two pushbuttons or with slowly reduce it to 0°. This is exactly what is done in this app.
optocouplers. Figure 12 shows the pulse sequence after a restart. The first
trigger pulse is generated approximately 8.6 ms after the zero
Soft start for inductive loads crossing. Another pulse is added ahead of it after each full
Inductive loads, especially transformers, can draw very high wave, until the time is reduced to around 0.3 ms. Figure 13
switch-on currents. Here switching at the voltage zero crossing shows the situation after settling down. Within the first 3 ms,
is the most difficult situation. The residual magnetisation of the the load current goes through zero due to the phase shift. In
core can also cause problems, because the switch-on current order to achieve a continuous current flow, it is necessary to
waveform may be offset from the zero line. As a result, the put the control pulses close together in this interval.
flux density in the core (the hysteresis loop) is shifted in one Figure 14 shows the transformer current with no load. The
direction and can easily enter the saturation region. When that zero crossing signal shows the relationship to the mains voltage.
occurs, the winding inductance suddenly drops to zero and the Here you can see the magnetisation current, which reaches
rising current is only limited by the resistance of the winding a maximum at the voltage zero crossing. The remaining part
and other elements. Ring-core transformers are especially prone results from the iron and copper losses of the transformer. The
to this. They should therefore be fused at a significantly higher phase lag of the current is not exactly 90°, due to losses and
level than what is required solely for the load current. nonlinearities in the core. Figure 15 shows the transformer
Sometimes a varistor or series resistor with a time-delay relay is current with a load. The load current and magnetisation current
used to limit the switch-on current until a symmetrical magnetic are superimposed. The load reduces the phase shift.
field (and correspondingly clean AC voltage) is established. A prerequisite for faultless operation is fully symmetrical control
In theory, this problem can also be encountered if the phase of the triac. The control pulses must have the same offset to
angle is slowly increased. When switching on the transformer, the zero crossing for both half-waves, so that the phase angle

24 May & June 2020 www.elektormagazine.com


About the Author
4 sale @ www.elektor.com
Roland Stiglmayr is an electronics engineer specialising
in information technology, with 40 years of professional ªElektor Arduino Uno R4
www.elektor.com/elektor-uno-r4
experience in R&D in the fields of control engineering, RF
engineering, mobile radio, fibre optics engineering and data
transmission. He is currently active as a consultant.

of the current is symmetrical. IGT and especially IH are signifi-  


cant for this. Reliable triggering is ensured by the RC network, We hope you enjoy
which strengthens the leading edge of the gate current pulse. the apps described here.
The transformer current must be greater than IH for the triac to Maybe you have an idea for
remain conducting. Ring-core transformers are difficult in this a new application? That’s easy
regard due to their high inductance. This problem can be solved to do by modifying the firmware.
by a small additional resistive load (R25-R27, optional). Some 190047-04
ring-core transformers even require an additional external load.
Particularly with transformers, driving the triac with pulses
alone was a challenge in the programming of the firmware.
The various tricks can be easily understood from the detailed
comments in the code.

Web Link
[1] Project support page:
www.elektormagazine.com/190047-04

Advertisement

Join the Elektor Community GOLD


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

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

Also available: ✔ Access to Elekt


✔ Access to over
or Archive
1,000 Gerber files
The all-paperless GREEN Membership! ✔ 10% Discount
in Elektor Store
✔ Exclusive Offer
www.elektor.com/member
s

EN A5 member advertisement 2020.indd 1 06/02/2020

www.elektormagazine.com May & June 2020 25


How-ToDownload
something from GitHub
GitHub for Dummies

By Clemens Valens (Elektor Labs)

If you use microcontrollers, play


with Arduino or do other things that
involve open-source software, you’re
sure to have come across GitHub.

GitHub is the place for people to share source


Although anyone should be able to use it, Github is intended for professional software
code for all sorts of open-source applications
developers and therefore has lots of functions that most people never need.
ranging from simple single-file Arduino sketches
to huge cloud applications consisting of many
repositories containing thousands of files, but
also other things like electronics design files or
simply text documents.

What is GitHub?
GitHub is a hub for git, where ’Git’ is a versioning
system, meaning it keeps track of changes made
to any document it’s aware of. The main purpose
of ’git’ and GitHub is to allow groups of people
to work together on the same software project.
Because GitHub is a tool for professional- and
production-quality software development, it has
lots of functions and options that most people
never need, and that make it complicated to use.

How to download from GitHub? The green ’Clone or download’ button is only visible in the root of the repository.
At Elektor too we publish code on GitHub and
tell people to download it from there. We then
often get the question “How do I download something from The green ’Clone or download’ button
GitHub?” This seems like a silly question to the experienced There is an easy download button, but it is only visible when
user, but it’s true, you cannot just download the files you see you are in the root of the repository. Once you are there things
listed in a repository. There is no Save or Download button, become easy: just click the green button labelled ’Clone or
and when you click on a file, it gets opened in a browser, not download’. However, you might get confused by the surprising
downloaded. If you right-click on a file and then save it, you options about ’cloning with HTTPS’, or open it on your desktop,
end up with a file containing HTML code, and not the contents or download ZIP. Here you just click ‘Download ZIP’ and ignore
you expected. the other stuff. You do not need to sign in or have an account.

Raw mode Arduino & GitHub


Actually, you can download a file if you open it in Raw mode first The name of the file you downloaded may end with ’-master’
and then right-click to save it as a file. Sadly that’s undoable and when you unpack it, you will get a folder with the same
in case there are a lot of files. name. Most of the time this doesn’t really matter, but it does

26 May & June 2020 www.elektormagazine.com


when the download happens to be an Arduino sketch. For the Cloning a repository
Arduino IDE the name of the .INO file must be the same as Finally, you can use the official GitHub method to download a
the name of the folder. The solution is simple: remove the project and that is by cloning it. In order for this to work you
’-master’ part by renaming the folder. must first instal a git client on your computer. There exist clients
with nice graphical user interfaces and clients that you control
Usually you do not have to do this when the sketch is inside a from the command line. In either case you will need the complete
folder nested inside the .ZIP file because the nested folder URL of the repository you want to clone. You can get it from the
will have the same name as the .INO file. download button, again, but this time by copying the URL in the
If the download is an Arduino library, then the Arduino IDE ’Clone with HTTPS’ box. Click the copy button next to it to do this.
knows how to deal with it. You can import it using the ’Add
.ZIP library’ option from the ’Sketch’ ’Include library’ menu. Command line (CLI) cloning
In the command-line interface, first navigate to the folder where
Releases you want your clone of the repository, then type the command
Many projects on GitHub are evolving continuously. If you ’git clone’ and paste the URL of the repository behind it and
download the .ZIP file as we did before, you get a so-called hit enter. If all is well, the cloning process will start. Example:
‘development snapshot’ that may not work or may not do what git clone https://github.com/ElektorLabs/180468-
you expect from it. ESP32-Weatherstation.git
For this reason, one tends to publish stable versions, so-called
releases, that work and have been tested. These releases are Open in desktop
often hosted on another website, for instance on the project’s In the desktop interface, from the menu select ‘File’ ‘Clone repos-
official website, but GitHub also offers space for them. Check the itory…’, browse to the destination folder and paste the URL you
Releases tab to see if there are any, and if there are, download copied before in the box labelled ‘Repository URL’, then click Clone.
the most recent one or another version or file you need.
You might also want to check the Releases tab if you’re not Cloning is easier than downloading
interested in the source code of the project, but only in precom- Once you know how to do it, then cloning is probably easier than
piled binaries to run on your platform. This is often the case downloading. You don’t have to unpack anything and you can
when compiling the project is too complex for you or even clone directly into the folder where you want it. And you don’t
impossible because you don’t have the tools for it. get the ‘-master’ added to the repository’s name either.
200047-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 May & June 2020 27


My IoT Button:
A Button for the Web
Part 2: Prototyping with board and cloud
By Dr Veikko Krypczyk (Germany)

The basic idea of an IoT button is that you use minimalistic


hardware to communicate with a remote service in the cloud. For
this it is necessary to establish a connection to a local network.
Small, low-cost microcontroller boards, such as the ESP8266
NodeMCU, are ideal for this task. Here we describe the relevant
aspects with regard to the IoT device and present some ideas
for your own projects. The nice thing is that it’s all relatively
easy to do, and the positive experiences come quickly. This creates
encouragement for developing your own projects.

The Internet of Things (IoT) makes all imaginable devices smart for requests. The client, which in this case is the IoT device,
and connects them to the outside world through the Internet. can send data to services (on a server) or request data from
In the first article of this series, we outlined the basic architec- services. In the second article of this series, we look at the
ture of an IoT landscape consisting of sensors, actuators, and a hardware and software aspects of the IoT device.
server backend. We saw that you usually do not have to set up
your own server infrastructure, since there are many options Selecting the hardware
available in the cloud. You communicate with them through What hardware should you use? There are basically several
the Internet. Things are really simple if you also adhere to the options — for example, a single-board computer such as the
established standards. RESTful communication is widely used Raspberry Pi. Along with WLAN, the RPi has enough process-

Figure 1: Pin assignments of the ESP8266 NodeMCU microcontroller Figure 2: Arduino IDE configuration for programming the ESP8266.
board.

28 May & June 2020 www.elektormagazine.com


ing power for all of the applications. If you want to use multiple Listing 1. ‘Hello World’ (blinking LED)
buttons, sensors and actuators in the same place with a variety on the ESP8266.
of functions, you can connect all these devices to the GPIO pins
of the Raspberry Pi. Then the RPi can establish a connection to #define LED D4           
the cloud service via the network. However, the Raspberry Pi void setup()
is physically too large for relatively small tasks, and it needs a {
continuous supply of power from an AC mains adapter.      pinMode(LED, OUTPUT);   
So let’s look at the Arduino Uno instead. As is well known, }
it is not a complete computer, but instead a microcontroller  
board. However, the hardware and software possibilities are void loop()
extensive and there are countless libraries and example appli- {
cations available. Programming is convenient in the Arduino     digitalWrite(LED, HIGH);
IDE. However, the Arduino board does not support WLAN, so
    delay(3000);            
you have to add an expansion board to get this capability.
    digitalWrite(LED, LOW); 
A much easier solution is to use the ESP8266 NodeMCU
    delay(1000);            
microcontroller board (see [1] and the inset). It has all the
necessary functions integrated, in particular a WLAN interface }
(Figure 1).
You only have to connect a pushbutton switch between an I/O
pin on the board and GND. Later on, pressing this pushbutton
will be communicated over the WLAN. A status LED is already
present on the board, so you don’t need any other compo-
nents. Power can be taken from the USB port of the computer,
at least for now.

Setting up the ESP8266 NodeMCU


Just like the Arduino boards, the ESP8266 microcontroller can
be programmed from the Arduino IDE. First you have to connect
the board through a data cable to the USB port of the PC, and
you may need to install the driver for the CH340 chipset [2]. If
you do not already have the Arduino IDE on your computer (in
which case you can skip this part), you need to install it now
Figure 3: Installation of the libraries for the ESP8266 NodeMCU board.
[3]. You also have to update the IDE with an add-on. Under
File Preferences, enter the link address [4] at Additional Board
Manager URLs on the Settings tab (Figure 2). Close the dialog
window with OK.
Now you have to do the actual installation in the Tools menu, The ESP8266 NodeMCU board
where you should find the entry Generic ESP8266 Module.
The ESP8266 NodeMCU is a microcontroller board with an
Select the Tools menu, click on Boards Manager at the top of
ESP8266 chip clocked at 80 MHz and up to 4 MB of flash
the pop-up menu, enter NodeMCU to limit the search range,
memory. The ESP8266 NodeMCU board also has WLAN
and then perform the installation (Figure 3).
module and a USB interface, including a USB to UART
Once this is done, you can test the board with a simple ‘Hello
converter (CH340G). This little board has the following
World’ program (Listing 1). For this, copy the code and then
technical features:
load it into the microcontroller with Sketch|Upload. In this
small routine, the LED on the board is alternately switched off
• Supports WPA/WPA2
for 3 seconds by the instruction digitalWrite(LED, HIGH) and
• Chip: ESP8266
switched on for 1 second by the instruction digitalWrite(LED,
• Processor: Tensilica L106 clocked at 80 MHz
LOW).
• System architecture: 32 bit, Flash memory: up to 4 MB
You also don’t need much code to query a pushbutton (in this
• Supported protocols: SPI, UART, I2C, I2S, IR remote
case connected to pin D7). For example, the following code
control, PWM, GPIO
section checks whether the switch is closed in order to trigger
• Logic level: 3.3 V
the subsequent actions:
• Current drain: <10 µA in sleep mode; up to 200 mA
under load
int button=D7;
• Supply voltage and programming via micro USB port: 5 V
status=digitalRead(button); • Programming chip: CH340G
if (status==LOW) • Size: 5.5 × 3.1 × 1.2 cm; Weight: 42 g
{ …… }
The above specifications make the ESP8266 NodeMCU
Now you have to give the ESP8266 access to the Internet. The
board a very suitable platform for small and especially low-
hardware for this is already present on the ESP8266 board,
power IoT devices.
in the form of the tiny grey-green WLAN module (Figure 4).

www.elektormagazine.com May & June 2020 29


Listing 2. Establish a link to the Internet.

include <ESP8266WiFi.h>
void setup()
{
    Serial.begin(115200);
   
    WiFi.begin(<SSID>, <Password>);
   
    while (WiFi.status() != WL_CONNECTED);
    {
        delay(1000);
        Serial.print("Connecting ...");
    }
}
Figure 4: ESP8266 NodeMCU board with WLAN module.

If you want to use the WLAN functionality of the ESP8266, you Data in the cloud
have insert the line #include ESP8266WiFi.h in the header A REST endpoint is required in order send data to the cloud,
of the source code to include the corresponding library. The which means to a remote server. You do not have to program
library expects the right data for establishing a connection to this yourself; you can instead use existing services. Most of
the Internet: the SSID and the password. For now you can do these cloud services are free of charge for tests and personal
put these in the source code as static data, but later on you use. Let’s proceed experimentally and step by step. At [5] you
will want to allow users to configure them. Establishing the can create a free REST API for test purposes, which can be
WLAN connection is remarkably simple (Listing 2). accessed from the microcontroller board via the WLAN. This
Now you should proceed with the design under the assumption works with just few mouse clicks, even without prior login.
that when an event is received, a message is sent via the network. Have a look under [6]; there you can see that we have already
A REST endpoint acts as the receiver of this network communica- created an endpoint (Figure 5). To test whether and how this
tion, as described in the first article of this series. This endpoint endpoint can be reached from the microcontroller, you can send
accepts the data or message and can further process it and initi- a GET request to the service when the button is pressed. This
ate a response. With a simple IoT button, the only data that has is implemented in the program loop (Listing 3).
to be sent is the ‘button press’ event. With suitable expansion of
this application, you could also sent additional data as parameters The following line in the source code checks whether the micro-
of the REST request. Now let’s see how it works. controller is connected to the Internet:

Listing 3. Send a GET request to the REST endpoint.         String payload = https.getString();
        Serial.println(payload);
void loop()
      }
{
      else
  if (WiFi.status() == WL_CONNECTED)
      {
  {    
        Serial.print("Error: ");
     status=digitalRead(button);
        Serial.println(httpCode);
     if (status==LOW)
      }
     {
      https.end();
      digitalWrite(LED, LOW); 
     
  
     }
      BearSSL::WiFiClientSecure client;
     else
      client.setInsecure();
     {
      HTTPClient https;
      digitalWrite(LED, HIGH);
      https.begin(client, "https://iotbutton.free.
     }
beeceptor.com");
     
      int httpCode = https.GET();
  }
      if (httpCode == 200)
}
      {

30 May & June 2020 www.elektormagazine.com


if (WiFi.status() == WL_CONNECTED)
{ …… }

This means that all the enclosed source code lines are executed
only if there is a connection to the Internet.
The next step checks whether the button has been pressed:

status=digitalRead(button);
     if (status==LOW)

If it has, an HTTP client is initialised, which enables the option


to send HTTPS commands. A library is required for this, and
it must be included in the header with #include. We set the
value https://iotbutton.free.beeceptor.com to indicate the
URL for our REST endpoint. This is followed by a simple GET
request to the endpoint, and the result is received as a charac-
ter string by the line

String payload = https.getString();

As a direct response to pressing the button, the LED on the


board should light up when the button is pressed and go dark
when the button is released (see above). You can check online
to see whether the data actually arrived in the cloud. Go to
the endpoint on the Beeceptor web page [6] and follow the
requests on the endpoint (Figure 6).
Bear in mind that only 50 requests per day can be sent free of
charge to the endpoint. During our experiments we exceeded Figure 5: REST endpoint for tests in the Beeceptor cloud.
this number, with the result that we received an error message
with the code 429 in response to the GET request. As long as
you do not exceed the maximum number of requests, the status
code 200 (okay) and the data of the REST request will be sent
back to the microcontroller. In the serial monitor of the devel-
opment environment (Tools/Serial Monitor), you can keep track
of the responses received by the microcontroller (Figure 7).
This proves that pressing the button sends a REST request
over the Internet. Now you have a working IoT button design.
Listing 4 shows the entire source code. The places that need
to be adapted to your individual situation are marked in bold.

Current consumption and sleep mode


We opted for the ESP8266 microcontroller in particular due
to its low current consumption. In practice you can assume Figure 6: Logged requests to the REST endpoint in the Beeceptor cloud.
the current consumption values given in [7]. With a simple
Arduino program the current consumption is approximately 50
to 70 mA, rising to around 80 to 170 mA in WLAN mode, and
for a few milliseconds the board can draw as much as 400 mA.
The possibility of considerably reducing the power demand in
deep sleep mode is therefore attractive. According to the data
sheet and Internet sources, values in the low microampere
range are possible, which means a simple battery (ordinary
or rechargeable) should be able to power the board for many
months. The supply voltage, for example from a powerbank,
can be connected to the +5 V and GND pins. There are two
forms of deep sleep mode:

• Software deep sleep: The ESP8266 automatically wakes


up after a specific time. For this, GPIO16 (D2) must be
connected to the RST pin. After the set time, a signal Figure 7: The responses of the REST endpoint are logged on the serial
is sent to automatically restart the ESP processor. The monitor. Here there is a 429 error message due to exceeding the number
maximum time duration with this option is approxi- of allowed requests.

www.elektormagazine.com May & June 2020 31


Listing 4. Send a GET request via REST.       BearSSL::WiFiClientSecure client;
      client.setInsecure();
#include <ESP8266WiFi.h>
      HTTPClient https;
#include <ESP8266HTTPClient.h>
      https.begin(client, "https://iotbutton.free.
#define LED D4           
beeceptor.com");
int button=D7;
      int httpCode = https.GET();
int status=1;
      if (httpCode == 200)
void setup()
      {
{
        String payload = https.getString();
    Serial.begin(115200);
        Serial.println(payload);
    pinMode(LED, OUTPUT);   
      }
    digitalWrite(LED, HIGH);     
      else
    WiFi.begin(<SSID>, <Password>);
      {
    while (WiFi.status() != WL_CONNECTED)
        Serial.print("Error: ");
    {
        Serial.println(httpCode);
        delay(1000);
      }
        Serial.print("Connecting ...");
      https.end();
    }
     
}
     }
 
     else
void loop()
     {
{
      digitalWrite(LED, HIGH);
  if (WiFi.status() == WL_CONNECTED)
     }     
  {    
  }
     status=digitalRead(button);
}
     if (status==LOW)
     {
      digitalWrite(LED, LOW);    

Listing 5. Send a GET request via REST and go into       BearSSL::WiFiClientSecure client;
deep sleep mode.       client.setInsecure();
#include <ESP8266WiFi.h>       HTTPClient https;
#include <ESP8266HTTPClient.h>       https.begin(client, "https://iotbutton.free.
  beeceptor.com");
#define LED D4              int httpCode = https.GET();
void setup()       if (httpCode == 200)
{       {
    Serial.begin(115200);         String payload = https.getString();
    pinMode(LED, OUTPUT);            Serial.println(payload);
    digitalWrite(LED, HIGH);               digitalWrite(LED, HIGH);
    WiFi.begin(<SSID>, <Password>);         delay(2000);
    while (WiFi.status() != WL_CONNECTED)         ESP.deepSleep(0);
    {       }
        delay(1000);       else
        Serial.print("Connecting ...");       {
    }         Serial.print("Error: ");
}         Serial.println(httpCode);
        }
void loop()       https.end();
{   }
  if (WiFi.status() == WL_CONNECTED) }
  {
      digitalWrite(LED, LOW);  

32 May & June 2020 www.elektormagazine.com


ESP8266 NodeMCU

A0 D0
RSV D1
RSV D2
D12 D3
D11 D4
INT 3V3
MO GND
MI D5
SCK D6
GND D7
3V3 D8
S1 EN D9
RST D10
GND GND
5V 3V3

Figure 8: The circuit diagram consists of the microcontroller board and a Figure 9: Collaboration between the IoT device, IoT cloud and other
single pushbutton. services, using ThingSpeak as an example.

mately 71 minutes. This option is a good choice in scenar- the code. Instead, the microcontroller is put into sleep mode
ios where periodically measured values are transmitted. after the data has been sent successfully over the REST inter-
The instruction for this is: ESP.deepSleep(SLEEP_TIME * face (Listing 5). Compile the source code (sketch) and load
1000000) it into the microcontroller. After starting up, the microcontrol-
• Interrupt deep sleep: The ESP8266 does not automatically ler connects to the network, sends a message, and goes into
restart, but instead is awakened from deep sleep mode sleep mode. When the microcontroller is awakened by the
by an interrupt. This form of deep sleep mode is initi- pushbutton (RST), this process is repeated from the beginning.
ated by ESP.deepSleep (0). In this case there must be no You can check online whether the GET request has reached
connection between GPIO16 and RST. When the event is the REST API.
triggered, a Low signal is sent to the RST pin. This restarts
the ESP8266, and the firmware is executed. Back in the cloud
  The basic IoT button implementation is ready now. The actions
For the IoT button, this means it is no longer necessary to to be taken when the microcontroller message is received can
connect the pushbutton to a GPIO pin. Instead it is connected be configured in a few further steps, because there are also
between the RST pin and ground, as shown in Figure 8. various cloud services available for these scenarios – such as
Consequently, there is no need to check for a button press in Microsoft Azure IoT [8][9][10] or ThingSpeak [11]. The proce-

Web Links
[1] ESP8266 NodeMCU user manual: www.handsontec.com/pdf_learn/esp8266-V10.pdf
[2] CH340 driver: https://sparks.gogo.co.nz/ch340.html
[3] Arduino IDE: http://www.arduino.cc/en/main/software
[4] Board manager URL: http://arduino.esp8266.com/stable/package_esp8266com_index.json
[5] Beeceptor: https://beeceptor.com/
[6] IoT button console: https://beeceptor.com/console/iotbutton
[7] ESP8266 current consumption: https://arduino-hannover.de/2018/07/25/die-tuecken-der-esp32-stromversorgung/
[8] Microsoft IoT cloud: https://azure.microsoft.com/en-en/services/iot-hub/
[9] ESP8266 in the Azure cloud:
https://sandervandevelde.wordpress.com/2019/05/07/connection-a-cheap-esp8266-to-azure-iot-central/
[10] NodeMCU in the Azure cloud:
https://www.thingforward.io/techblog/2018-05-22-connecting-nodemcu-to-microsoft-azure-iot-hub-part-1.html
[11] ThingSpeak: https://thingspeak.com/

www.elektormagazine.com May & June 2020 33


Figure 10: Configuring a REST endpoint (channel) at ThingSpeak. Figure 11: At ThingSpeak, the actions for a channel are determined by
apps.

dure essentially consists of configuring an endpoint directly in the IoT project ready for production, or even turn it into a
the cloud service and then contacting it with the IoT device via commercial application. This mainly involves minor mechan-
the Internet. Then the desired actions can be initiated through ical peripherals (enclosure) and the power supply (perma-
the service (Figure 9). nent battery connection). Extensions are also conceivable. For
You can set up a free account for the ThingSpeak service, which example, replacing the pushbutton by a motion detector would
only requires verification of an email address, and then create allow the device to generate an alarm and communicate it
a new REST endpoint (channel). via the Internet when an unauthorised person approaches a
Fill in the detailed form, which is explained to the right secured property. The actual work is done online through the
(Figure 10), or first give your newly created endpoint a name. configuration in the cloud.
Each channel is given a unique URL and the ability to not only (190303-B-04)
receive requests but also send additional data by means of URL
parameters. Although no additional parameters are needed for
a simple IoT button, the channel read and write keys (as well
as example application for how to include the keys in the GET
requests) can be found under My Channels/API Keys. Once a
channel is correctly configured, you can use the menu item Apps
to define which actions should be triggered (Figure 11) — for
example, sending an email via a web service or posting a tweet
on Twitter. Here the IoT backend acts a sort of intermediary.

Hazard warning: IoT devices that communicate with services


on the web need access to these services. For this purpose,
they have to identify themselves, for example with a user name
and password or with unique features (keys). These values
must be stored in the source code. Be sure to keep this infor-
mation protected, for example when copying the source code
or publishing it on the Internet (for general use).
4 sale @ www.elektor.com
Conclusion and outlook
Experimenting with the ESP8266 microcontroller is fascinating. ªESP8266 NodeMCU
www.elektor.com/17952
Few if any additional components are necessary to implement
IoT scenarios. Not much more work would be needed to make

34 May & June 2020 www.elektormagazine.com


TMS0280 Speech Synthesizer
Peculiar Parts, the series
By Neil Gruending (Canada)

In 1976 Texas Instruments (TI) wanted to design a device


that would pronounce a word to be spelt out on a keyboard
as a way to teach spelling. It needed to be inexpensive, so it
needed to store as many words as possible in about 256 kbits
of memory. It also needed to be portable, so the size and
power consumption was also very important. By 1978 TI had
managed pack the apparent performance of a several-thous-
and-dollar computer into the $50 device that we all know as
the Speak & Spell thanks to the TMS0280 speech synthesis IC.
TI already had the TMS1000 microcontroller that we looked
at in the previous installment but is wasn’t powerful enough
to do speech synthesis on its own. For that TI turned to their
team that included Larry Brantingham, Paul Breedlove, Richard
Wiggins and Gene Frantz. After a lot of research, they deter-
mined that consumers associated a dull monotone voice with
computer generated speech which worked in their favour to
greatly simplify the synthesis requirements. The result was
the TMS0280 which used linear predictive coding to generate
speech at a 10-kHz sample rate from audio data encoded at
1200 bits per second.

Figure 2: TI Speak & Spell. Author attribution: Bill Bertram 2006. No


changes made. CC-BY-2.5 — Attribution: https://creativecommons.org/
licenses/by-sa/2.5/deed.en

The encoded data was stored as data frames that contained


information like energy, pitch, and reflection coefficients that
were needed for the speech algorithms. Sometimes the data
frames were hand-generated in the lab but usually the encoding
parameters were generated by large computer programs that
analyzed real speech data. Either way, the goal was to create
encoded data that could be clearly understood and sounded
as close to the original speech as possible.
The TMS0280 contained a digital signal processor with a multi-
plier, an adder implementation of a two multiply lattice filter
and a masked ROM for the program memory. The ROM allowed
the data rate, excitation and filter characteristics to be changed
as needed for different production variations. It also contained
an oscillator, interface logic and a 200-mW D/A convertor for
the audio output.
Now obviously TI hasn’t produced the Speak & Spell for about
30 years but there’s a strong enthusiast community modifying
them. Probably the most famous one was the Speak & Spell that
E.T. used to call home in the movie E.T. The Extra-Terrestrial
— TI even made a special themed language cart based on the
movie. So maybe it’s time to take that Speak & Spell that’s been
Figure 1: TMC0280 labelled TMC0281 in a Speak & Spell. hiding in a box and see what you can do with its TMC0280.
Source: Datamath. 190383-C-01

www.elektormagazine.com May & June 2020 35


Interactive
Corrections & Updates || Questions & Answers
By Clemens Valens (Elektor Labs)

Updates of and additions to projects published in ElektorLabs Magazine spiced up with tips & tricks, tech
advice, and answers to reader's questions.

Upgrade for the 3-way Display Alarm


Elektor Labs magazine 3/2019 (May &
June), p. 52 (180620)

It’s me again with a reader tip from the field. The article
states that the RTC BoB is too tall to simply replace the
DS1302 (IC2) of the clock. It then goes on to mention
three possible ways to modify the clock to make the BoB
fit. I have found a fourth possibility which I personally
consider to be the best because it does not require any
changes to the clock at all as it fits in place of the exist-
ing IC. The trick is not to use the pinheaders shown, but
to use cut off component wires, plenty of which should
be around in the electronics enthusiast’s work area.
Once the BoB is equipped with its three components,
place it — component-side facing down — on top of
an 8-pin IC socket. Then stick eight wires from above
through the board’s holes into the contacts of the socket,
as shown in the photo. Using a pair of small, flat pliers
is better for your fingers and makes it easier to ensure
that all pins go down all the way into the contacts. Cut
the wires flush with the little PBC and solder them. Carefully lever the BoB out of the helper socket and insert it into the socket
for IC2 on the clock PCB. As you can also see on the photo, the RTC is now even lower than the original IC.
Hans Schneider (Germany)

Flicker-free LED Dimmer


Elektor Labs magazine 5/2019 (September
& October), p. 12 (190062)

Even though I enjoyed reading the article, I felt that


it was not complete as it doesn’t mention that the two
advantages of the method, i.e. less flicker and better
EMC, are offset by two disadvantages.
First of all, the colour of an LED depends on the operat-
ing current. The principle proposed by J. Waegebaert
changes the operating current and thus the colour
of the light produced. This can be disturbing in, for
example, professional photography. When operating
with rectangular-pulsed current (PWM), the individual
current pulses always have the same value. Therefore,
the resulting colour of the light does not change in this
operating mode, and remains constant over the entire
dimming range.
Second, smooth dimming in the lower brightness range

36 May & June 2020 www.elektormagazine.com


is not guaranteed. Not all power LEDs have a defined behaviour in the lower current range. There are manufacturers who
specify a minimum current 10% up the nominal current (for example). With pulsed current it is still possible to dim smoothly
down to zero.
In practice one will have to find a suitable compromise for each application.
Daniel E. (Switzerland)

Single-phase 1-kilowatt AC Motor Drive


Elektor Labs magazine 1/2020 (January & February), p. 62 (191142, 150199).
In the circuit diagram in Figure 1, the ‘+’ and ‘–’ symbols shown inside
the symbol for bridge rectifier B4 should be swapped.
In the circuit diagram in Figure 2, it is not immediately evident that
the SDA and SCL pins on display OLED1 are connected to pins 23 and
18 respectively of microcontroller IC2.
The component list incorrectly identifies power
transformer TR1 as a Myrra 44327; the correct
number is 44237.
Finally, contrary to what is said in the
article text, the power electronics
board is double-sided.

None of the above advice


has any consequence for
the operation of the project, or
the associated PCBs available from
the Elektor Store.
www.elektor-labs.com/3980

ESP32-PICO-Kit v4.1 Cannot Be Programmed With Arduino IDE?


Q: The two ESP32-PICO-Kit modules I bought last month have a version number of 4.1. The modules I bought earlier are
version 4. The older modules can still be programmed with the Arduino IDE. With the new ones however I was able to upload
just one sketch, and then uploading stopped working. The uploaded sketch ran correctly. I have tried different baud rates.
What can be the problem?
S. Kepper (Germany)

A: The two modules that you sent us can


be programmed on our test system without
any problem. However, we did discover
that there appears to be a driver or other
software problem with certain combinations
of Windows 10 and USB controllers (AMD Ryzen
platform). Unfortunately, we have no control
over these components. As a workaround, the
behaviour can be improved by using an old
USB 2.0 hub.
Elektor Labs

Epilogue: Many thanks for your reply. Your answer incited me to take a closer look at the USB ports on my PC. It has both
USB 2.0 and USB 3.0 interfaces. I have found that I can/may not use USB 3.0 under Windows 7 for the newer ESP32-PICO-
Kit 4.1 modules. Maybe this discovery is also interesting for other users. Why programming the module the first time on a
USB 3.0 port worked, remains a mystery.
S. Kepper (Germany)
190379-C-01

www.elektormagazine.com May & June 2020 37


BASIC
for the ESP32/ESP8266 (2)
An hourglass with the ESP8266 and Annex WiFi RDS

By Peter Neufeld (Germany)

In the previous edition of Elektor,


Annex WiFi RDS was described
as a platform for programming
ESP8266/ESP32 controllers
in BASIC. Now we are talking
about a practical application: the
firmware for an auto-rotating
hourglass — not in C, C# or C++,
but in fast, straightforward and
simple BASIC.

Figure 1: On the finished hourglass a four-digit


digital clock lights up on the left and on the
right a real and illuminated hourglass is turned
by a hidden servo at the exact time.

The BASIC development environment for the rather complicated programming A simple project
Annex WiFi RDS [2] described in Elektor of modern SoCs. To realize a digital clock with the ESP8266
March & April 2020 [1] is now available You can choose between different that displays the weather forecast at the
as a practical entry project. The ESP8266 programming languages, various IDEs, same time is a matter of a few BASIC
modules, available in various designs for libraries, drivers, resources and compil- lines, as example projects on the Annex
little money, open up endless possibili- ers. Or should you sneak past them and website [3] prove. I came up with a
ties for the electronics engineer projects take some unfamiliar code that is difficult simple idea with special elegance: the
of many levels, not only thanks to their to understand and somehow transfer it combination of a digital and an analogue
WLAN capability, but also because they to the module? It gets really complicated display. In the project “ESP8266 Sand
can be easily connected “wirelessly” to if you want to control your project via Clock”, a small one-minute hourglass
smartphones, tablets and PCs. Since web interface with a smartphone. The located next to a conventional four-digit
there are also various sensors and development environment called Annex digital clock, is to be turned over
actuators that can be easily connected WiFi RDS makes such a project much precisely in time.
to the microcontroller for little money, simpler by using the BASIC program- But that’s not all: the trickling sand could
do-it-yourself construction could actually ming language. This in turn leads to quick be illuminated. Four NeoPixel LEDs are
be a real pleasure again — if it weren’t achievements. used as background lighting. Of course,

38 May & June 2020 www.elektormagazine.com


the display’s brightness should be
adjusted to the surroundings, to which
+3V3
an LDR is added as a light sensor. If you
add a 1-wire temperature sensor, you
can even show the room temperature R2 SERVO
4k7
on the display. SG90
Of course, the hourglass should also
4W WS 2812B
be controllable via WLAN using the IC1 R3 R4 + S
MOD1 LED1
integrated web interface. If you think of DP1 10k 10k
3V3 D6 D5 A
LDR LED2 CLK
D1-Mini
the code and the many potential bugs,

USB
LED3 Dio
ESP8266
R1

GND
D4 D3 D2 D1 VCC

5V
sometimes it’s just a heroic approach 47k DS18B20
LED4 GND
- +
forever scheduled to mañana ;-). TM1637
+5V
But because the ’real thing’ is much
easier thanks to BASIC, the finished C1
hourglass shown in Figure 1 doesn’t 22µ C2
need as much software work as one 10V 22µ/10V GND
might think.
190400-022-94
Browsing the extensive, practice-oriented
help file for Annex WiFi RDS, includ-
ing the contents of the corresponding Figure 2: The electronic hourglass circuit is really this simple: in addition to the ESP8266 module,
website, gave me some ideas for new four resistors, two capacitors, four LEDs, a temperature sensor, a display and a servo are required.
projects. Despite its power, BASIC is easy A parts list is not necessary.
to master even for casual programmers.
Thanks to the Annex Rapid Development
Suite, software development is consider-
ably simplified compared to other current
solutions.

The electronics
The D1-Mini controller board used
offers an ESP8266 module and, thanks
to its pins, is suitable for experiments
on a breadboard, as all relevant SoC
connections are brought out. Via its
USB interface and auto-flash capability,
the module is easily and quickly loaded
with firmware using the Annex Toolkit
[4] without hardware intervention. Don’t
forget to set the correct time zone on the
CONFIG page and enter the BASIC script
in the autostart line there (the path of Figure 3: The test setup of the hourglass on a breadboard according to the circuit of Figure 2.
my active script is always “/program/
default.bas”).
For my tests I built the circuit from
Figure 2 on a breadboard. The result Therefore almost all external pull-up BASIC software
can be admired in Figure 3. resistors are connected to +3V3. The After one-time installation of the
If the supply voltage is connected via internal voltage divider of the analogue firmware on the ESP8266 using the
the micro USB socket, +5 V and +3.3 V input ensures that voltages from 0 to Annex Toolkit [4] and following the
are also brought out and both voltages 3.3 V can be processed and that even instructions in [5], you only need a web
are additionally loadable (within limits), 5-V swings do not cause problems. The browser to access the module’s web
thanks to a Schottky diode and a 3.3 V voltage divider with the LDR should be server. New code can be quickly written
voltage regulator inserted. The currents dimensioned in such a way that with full in the editor or inserted into default.bas
required for the peripherals used here lighting, no more than 500 mV appears at by using copy & paste.
do not push this to the limit. If you want the input. If the analogue input remains In the Annex help file (F2 key in the
to be absolutely sure, you can power unconnected, 0 V is applied here and editor) you will find explanations, pin
the servo separately from +5 V. The two the display is consequently set to full assignments and script snippets for the
electrolytic capacitors between +5 V and brightness. TM1637 LED display, the analogue servo,
ground absorb the current peaks of the Caution when connecting the tempera- the NeoPixel LEDs and various commer-
servo. ture sensor DS18B20! The unit with cially available actuators and sensors as
Please note that the inputs of an ESP8266 module board has a different pin configu- well as for the different ESP modules.
can handle a 3.3 V level maximum. ration than the sensor in the TO housing. The online help also contains a helpful

www.elektormagazine.com May & June 2020 39


improve it in a few weeks. The complete
Listing 1. Preamble of hourglass.bas
code is available for download on the
'#################### HOURGLASS ######################### Elektor website for this article [6].
' 4Digit digital clock combined with 10 minutes hourglass In the constant change from opening
  VERSION$      = "V3.3" the file default.bas, editing, storing (!),
' 10/2019  [email protected]   min:ANNEX_1.39b6 starting, debugging, debugging, extend-
' - ESP8266-Module: WEMOS-D1-Mini ing, saving, starting etc. common errors
' - Display: 4digit 7segment TM1637
in the code are named and marked by
the interpreter. They are then usually
' - Servo: analog servo (SG90)
corrected in no time. The BASIC code
' – Background light: 4 NeoPixel-LEDs
can be readily understood by casual
' – Temperature sensor: DS18B20
programmers if meaningful variable
' – Light sensor: LDR @ analogue input names are assigned and subroutines
' GPIO-Mapping (PIN-Label) for WEMOS and NodeMCU boards are used. BASIC is just easy to read.
D0=16:D1= 5:D2= 4:D3= 0:D4=2 Automatic code highlighting improves
D5=14:D6=12:D7=13:D8=15:D9=3:D10=1 readability and facilitates syntax check-
SERVO_PIN   = D5  'Servo @ GPIO14=D5 ing. For syntax problems, the F2 key
TM_DATA     = D2  'TM1637 Data @ GPIO4=D2 helps with its context-sensitive search in
TM_CLOCK    = D1  'TM1637 Clock @ GPIO5=D1 the online help file. There is also a small
TM_BRIGHT   = 7   'TM1637 brightness green check mark in the editor window
TURN_TIME   = 10  'Turn hourglass every xx minutes
that leads to the syntax check.
The BASIC script is initially quite linear.
SERVO_LEFT  = 180 '1. Position of hourglass
After initialization of some variables and
SERVO_RIGHT = 0   '2. Position of hourglass
a short movement of the hourglass servo,
SERVO_POS   = 0   'actual position of hourglass
the IP address of the Annex web server
BLINK       = 0   '255= visible colon @ TM1637 is shown in portions on the display.
ADC_DARK    = 450 'max. ADC value for dark LDR, This helps a lot when accessing the
'            depends on LDR and Pull-up server with a web browser, especially
LED1_STATUS = 0 'Background LEDs: 0=automatic, 1=manually if the router has assigned a different IP
STATUS$     = "Modus: AUTOMATIK" address.
ADC_IN = 0:
The main routine is processed once per
second by a timer. Hours and minutes
are processed to suit the display, and
section on the basics of the language. This project quickly resulted in about 140 the subroutines for light control and
In Listing 1 the start of the used BASIC lines of BASIC. Since they are provided backlighting, the display of time and
script is presented. Listing 2 contains with sufficient comments, you can follow temperature, and every ten minutes
the code of the deliberately simple web such a script even if you didn’t write the servo control are called sequentially.
interface, which can be seen in Figure 4. it yourself or if you want to extend or I abandoned my original plan to turn
the hourglass once per minute when I
noticed how loud a model-making servo
is when it turns the hourglass in the living
Listing 2. The deliberately simple web interface.
room. So I decided to use a ten-minute
WEB_PAGE: hourglass, which turns the glass slowly
cls over approximately four seconds and
a$ = "<center><h1> - S A N D U H R - "+ VERSION$ +" - </h1>" thus more quietly and less frequently.
a$ = a$ + "<br>" + textbox$(t$,"cssTB")   If you like that, you can also use a faster
a$ = a$ + METER$(SS,0,60,"cssMET") hourglass to achieve a one- or five-min-
a$ = a$ + textbox$(TEMP$,"cssTB")+"<br><br>"
ute rhythm via the variable TURN_TIME.

a$ = a$ + "<br>R: "+ slider$(R, 0,255)+ textbox$(R,"cssTB")


Web interface
a$ = a$ + "<br>G: "+ slider$(G, 0,255)+ textbox$(G,"cssTB")
When a web browser first accesses or
a$ = a$ + "<br>B: "+ slider$(B, 0,255)+ textbox$(B,"cssTB")  
re-accesses the ESP8266 web page,
a$ = a$ + "<br>"+ LED$(LED1_STATUS) or when variable values used change,
a$ = a$ + "<br>"+ textbox$(STATUS$) the HTML content of the ESP8266 web
a$ = a$ + "<br>"+ BUTTON$("Umschaltung auto/manuell",MAN_AUTO) page is prepared and updated in the
a$ = a$ + cssid$("cssTB"," width:70px;text-align:center") WEB_PAGE subroutine (see Listing 2). The
a$ = a$ + cssid$("cssMET"," transform:rotate(-90deg);") web interface shows the current time and
html a$ temperature. The simple LED background
return animation behind the hourglass is
replaced by a manual RGB colour selec-

40 May & June 2020 www.elektormagazine.com


Figure 4: A simple web interface can be realized with a whiff of BASIC Figure 5: This is how the electronic hourglass looks from behind: not
code. Sanduhr = hourglass; Modus = mode; Umschaltung = toggle. pretty, but working, assembled in flying-wire style.

tion via pushbutton. In automatic mode, LED display segments are visible and the Other frames with plexiglass fronts (e.g.
the RGB controllers and display fields LDR light sensor can also absorb suffi- from the range of a large take-away
follow the continuously calculated values cient ambient light. The servo axis for furniture store) could also be used as
of the animation live. the hourglass was guided through a small an alternative. The transparent front
The website is only intended to demon- hole in the screen. With appropriately cut can then be backed on the inside with
strate here by way of example how sections of foam rubber plates or black a transparent paper or a suitable photo
the Annex firmware in the background paper the light transmission of the front print.
handles the bidirectional communica- material is limited to the necessary zones 190400-B-04
tion with the web browser. The Annex- on the display, behind the hourglass and
supported use of CSS (Javascript, AJAX on the LDR.
and web sockets are also supported)
means that there are virtually no
limits to experiments in communica-
tion with (almost) any web browser.
There are also many examples of this
4 sale @ www.elektor.com
on the Annex website — especially in ªWeMos D1 mini Pro
the files that can be copied from the www.elektor.com/wemos-d1-mini-pro-esp8266-based-wifi-module  
Annex Toolkit to the /program direc- ªBook: IoT Home Hacks with ESP8266
tory on the ESP module during firmware www.elektor.com/iot-home-hacks-with-esp8266
installation. It’s worth browsing! An ªPDF file: ESP32 & ESP8266 Compilation
interesting script can be inserted, saved www.elektor.com/esp32-esp8266-kompilation-en
and started quickly in default.bas in
the Annex Editor window with a text
editor (e.g. GEANY.exe) for testing via
“crtl+a” (select all) as well as copy &
Web Links
paste! Complete sections of the script
can be quickly converted into comment [1] BASIC for the ESP32 and ESP8266 (1):
lines from the menu and vice versa. www.elektormagazine.com/190400-03
[2] Annex WiFi RDS: https://sites.google.com/site/annexwifi/home
Moving to the final housing
[3] Example projects: https://sites.google.com/site/annexwifi/projects
The tested circuit was finally installed
without any circuit board or breadboard [4] Toolkit: https://sites.google.com/site/annexwifi/downloads
in a small wooden frame, covered with [5] Manual: https://sites.google.com/site/annexwifi/home/first-steps
a translucent canvas on the front side [6] Article web page: www.elektormagazine.com/190400-B-04
Figure 5). Thus only the active, luminous

www.elektormagazine.com May & June 2020 41


Developer’s Zone
Tips & Tricks, Best Practices and Other Useful Information
By Clemens Valens (Elektor Labs)

From Idea to Product


Even though it seems that our new product design advances rather slowly, it’s unlikely to move
quicker in the real world. Setting up a business takes time. The previous installment left us with
Part 5
a Bill of Materials (BoM) and a netlist, and so we can now start working on a printed circuit board
(PCB) for the project. Or several, as needed. Please note that PCB designing is highly complex and cannot be treated in
any depth in this short article. Please refer to [1] for more information on, and suggestions for, PCB design work.

Start at the end


One of the first things we did in this article series was parts as closely to each other as the routing allows, and then
creating a mock-up of our future product. With this dummy in shrink the outline to get the smallest board as possible. Next,
mind, we designed the electronic circuitry to put into it, and the board is etched, populated and tested and finally put into
consequently we only selected components that fit inside and the enclosure. It then turns out that there either are no or
are adapted to the product’s intended working environment. insufficient mounting holes, or they are not in the right place,
Now we are going to add one or more PCBs to the mix, and and not of the correct diameter. Furthermore, connectors
they will have to fit as well. Therefore, before you start are at the wrong side and cooling is not possible. In short,
placing parts and routing traces you should think about the you created a mechanical nightmare, and the board is up for
board’s outline and mounting holes, or other ways of keeping revision. Most of this could have been avoided if the product’s
the PCB in place inside its enclosure. future enclosure had been on the desk of the PCB designer.
Often people simply start with a rectangular outline, place the

Enjoy your freedom


The interesting thing about PCB design is its
combining of disciplines like electronic and
Design
mechanical engineering. It is about designing
a mechanical part with particular
for production
It’s tempting to build in safety margins when
electronic properties and you, as the
designing a footprint; you know, make a
designer, have (almost) full control
pad slightly larger than specified, a hole a
over it. So do make use of the
bit wider, that sort of thing. This sounds like
possibilities PCB design
a good idea, but it may very well result in
offers you. A PCB can be
problems during automated manufacturing.
part of the enclosure,
Oversized SMD pads can make parts drift out
it can be made from
of position or rotate during reflow soldering.
aluminium, it can be The enclosure of the
legendary Elektor ’TAPIR’ Or the excess solder paste may cause short
flexible, it can have
E-smog detector was entirely circuits. Holes with a diameter much larger
almost any shape.
made out of PCB material. than the lead passing through it may not
Because the boards you
wave-solder properly.
see in Elektor are often
rectangular doesn’t mean that they must be like that.

42 May & June 2020 www.elektormagazine.com


Can you trust your parts?
Besides ignoring mechanical compatibility, another very
common PCB design problem are wrong footprints. The
problem is similar to the one we came across during
schematic capture. If you stick to passive components in
0805 packages and use SOT-23 transistors and diodes only
you will probably be okay, but chances are that you will
have to design at least one custom footprint because your
CAD software doesn’t have it in its libraries. Repeating the
wise words from the previous installment: “Searching the
Internet may be a quick solution,
but can you trust clemo12345?
Buying them from a commercial It’s surprising how confusing
schematic/PCB CAD part supplier datasheets can be, when it could
have been so limpid.
may be better, but will cost money.
In any case, you should carefully
check every component before
dreaming of relying on it. This is
also true for standard library parts
as libraries may contain errors.”
Besides downloading the datasheet of datasheets can be about diameters (pin or hole?), bottom or
every part of your design, it is also highly recommended top view, inches or millimetres, pin numbering, etc. And they
to get samples of each and every one of them before may contain errors too. Having the real thing in your hand
commencing the board design. It is surprising how unclear will save a lot of mistakes.

Talk to the assembly house


Besides soldering problems due to incorrect footprints, instance, the addition of snap-off tabs to the board. There
component placement may also hinder the assembly process. are also parts that have special soldering requirements. Most
A large metal part next to a tiny plastic one may result in of these problems can be solved by the people at the PCB
bad soldering of the first, or damaging the second due to assembly house, but if you consult them before finalizing the
the uneven heat requirements. Part positions may not be PCB, the board may turn out cheaper and faster to produce,
compatible with the pick and place machine, requiring, for as well as more reliable.

Board iterations
are expensive Beware of
Chances are high that the first version of your PCB will
need a few tweaks. To allow you to keep track of different mirrored footprints!
board iterations, mark and label them clearly. Do not The mirrored-footprint error is so common that it merits
forget to update the version number on the board every having its own paragraph header. Explaining it is not
time you change it. It’s also recommended to write down necessary, you know what I mean; just stop making this
the changes and their causes. Volume quantities tend to mistake. End of paragraph.
increase as confidence in the product grows. This makes the
product cheaper, but it makes modifications more perilous.
Discarding ten prototypes is probably less expensive than
replacing one resistor with a wrong value on 1,000 boards
pulled from a production run. No longer remembering
exactly why that resistor value was changed doesn’t make
things any easier.
What’s next?
Our product is almost ready, or is it? We now have a few
prototypes to test and to play with. Testing, you said? Yup.
Testing for functionality, for certification, for quality — there
Web Link is a lot of testing to do. So how do you do that? And what
are the implications? Will this article series never end?
[1] PCB Design is Not Easy:
190369-C-01
www.elektormagazine.com/160397

www.elektormagazine.com May & June 2020 43


Cricket Thermometer and Dolbear’s Law

At the risk of repeating myself, temperature may well be the T = N15 + 40 [°F]
world’s most surveyed physical quantity. Several methods exist
to measure temperature. In electronics the most common ways Here N15 is the number of chirps in 15 seconds. Converted (and
to do it are: rounded) to Celsius gives:
• thermistor: a device whose resistance increases (positive
temperature coefficient or PTC) or decreases (NTC) with T = N8 + 5 [°C]
temperature;
• Resistance Temperature Detector (RTD): exploits the Here N8 is the number of chirps in 8 seconds. The cricket ther-
precisely known relationship between temperature and mometer is fairly accurate between 5 and 30°C.
resistance of a material, typically a metal like platinum;
• thermocouple: a junction of two different metals that Cricket Emulator
produces a temperature-dependent voltage as a result of Just for fun, using an Arduino Uno, a passive buzzer and a
the thermoelectric (Seebeck) effect; DS18B20 one-wire temperature sensor, I inverted the process
• semiconductor-based sensors: the voltage across a to emulate a cricket based on the ambient temperature. Now this
diode or PN junction decreases by approximately 1 to 2 mV looks like a silly project and, to be honest, that’s how it started.
per degree Celsius; However, once I had it up and running, I quickly noticed how
• infrared thermometer: infers temperature from thermal sensitive the human ear is to rate changes. In the end I think
radiation. this emulator could make for a useful temperature indicator in
applications where it is not practical to keep an eye on a display.
The last technique is often used to measure human body tem-
perature by pointing a ‘temperature gun’ at the insides of an ear. Full project details can be found at: www.elektor-labs.com/3945
Up to this point nothing new, you say, discreetly suppressing a
yawn, but did you know that you can use the ear itself to deter-
mine the temperature?
As it turns out, the chirping sound produced by a cricket is tem-
perature dependent. Similar to estimating the distance of a thun-
derstorm by counting the seconds between a lightning flash and
the thunder that follows it, the temperature of the air can be esti-
mated by counting the number of chirps produced by a cricket in
one minute. This correlation was reported in 1881 by Margarette
W. Brooks, but the credit went to Amos Dolbear after he published
an article entitled “The Cricket as a Thermometer” in 1897. The
green tree cricket officially known as Oecanthus fultoni has been
known as the thermometer cricket ever since.
Calculating the temperature T from the cricket chirp rate is easy, Not all temperature sensors are created equal. This 24-hour log shows the outputs
especially in Fahrenheit: from a DHT-22 and a DS18B20 sensor placed next to each other.

44 May & June 2020 www.elektormagazine.com


HOMELAB PROJECT

BalBot
a Self-Balancing Robot
Modern acceleration sensors ease
the construction process

By Dr Günter Spanner (Germany)

Regulations are not only prevalent


in technology, but are also commonly
found in nature. The construction
of self-balancing robots can serve as
a preliminary stage of androids, since
movement on two parallel wheels
requires a control similar to that
of the walking upright. In this
project, an Arduino Uno and an IC
comprising an acceleration sensor
and a gyroscope are employed.

In contrast to technology and science, in


everyday life a distinction is rarely made
between regulation and control. A mere control
system does not monitor the output value, meaning
that it can change due to external disturbances. A
simple and typical example is the speed control of a DC
motor by PWM. Here, the speed of the motor is also influenced
by load fluctuations.
Now to the control: If a speed is to be kept constant, feedback
is required, for example to adjust a controlling PWM or DC
voltage depending on the speed deviation. Such a feedback
system characterizes a control loop.
Control therefore means that the output variable (e.g. speed)
is captured and, in the event of a deviation from the target

www.elektormagazine.com May & June 2020 45


Figure 1. Wiring diagram of the BalBot. The Bluetooth module and the Figure 2. Principle of self-balancing.
potentiometer are optional.

Balance on one axis


An interesting example for the application of such controls is
component list a self-balancing robot. In principle, this is an inverse pendu-
lum on wheels. Due to its instability, the inverse pendulum is
a classic example for the application of an active control loop.
The well-known Segway scooter is a one-axle, two-wheeled,
electric vehicle. The person to be transported stands between
the wheels virtually on the axle. In principle, single-axle vehicles
are unstable. So a control system provides the necessary
balance. Driving it is fun. The popularity of such scooters then
triggered the development of self-balancing robots.

To reproduce a scooter according to the Segway principle is


not really difficult. There are even complete kits. However,
it does not necessarily have to be such a scooter to deal
value, the manipulated variable (here the PWM) is changed with the underlying control technology: For this purpose,
accordingly. The central terms are: it is sufficient to build a smaller, self-balancing robot, as
described below.
• Actual value: x
• Required value: w In order for a self-balancing robot to maintain its balance, its
• Control deviation: e = w - x wheels must permanently counteract the tendency to tilt. This
• Manipulated variable: y requires a dedicated control loop, a sensor and actuators. The
• Disturbance variable: z IC MPU-6050 is perfectly suited as a sensor element, contain-
  ing an acceleration sensor and a gyroscope. This allows very
These variables are sufficient to describe a controller. precise measurement of acceleration and rotation in the three
There are also controller types with different control charac- three-dimensional axes. Since such chips are used in many
teristics. The PID controller is very common and covers many devices such as cameras or smartphones, mass production
cases. It has a proportional (P) as well as an integral (I) and a makes them low in price. An Arduino Uno is all you need to
differential (D) path. By adjusting its parameters, many control calculate the data. The motors coupled to the wheels are the
engineering problems can be solved with high precision. actuators.

46 May & June 2020 www.elektormagazine.com


If the MPU6050 is connected to an Arduino (see bottom left
in Figure 1), the correct function can be checked with a test
program. The download archive accompanying this article [1]
contains „MPU6050_test“ for this purpose. After loading the
test program the serial monitor of the Arduino IDE can be
started. Six lines show the reaction of the sensor values to
rotation or movement. If correct motion data is displayed, the
motor driver can be connected to the Arduino. The type L298N
(the IC or a module equipped with it) is appropriate as driver
for small DC motors. The power source is either seven 1.2 V
NiMH (= 8.4 V) or two 3.7 V LiPo batteries (= 7.4 V). Figure 1
shows how the individual components and modules (see parts
list) are interconnected.

Balancing algorithms
As already mentioned, a suitable control loop is required. The
position of the robot corresponds to the actual size. It should Figure 3: Tilt angle curve in the serial plotter integrated in the Arduino IDE.
deviate as little as possible from the vertical (target size). A PID
controller is ideal for this. Our robot named BalBot achieves an
astoundingly stable dynamic balance with optimally adjusted
Kp, Ki and Kd parameters. The target value or the vertical is 6. In the main loop, only the MPU signal is read out,
first fixed in the software. Figure 2 illustrates how this works and the control signal for the motors is computed
in practice. u s i n g t h e P I D c o n t r o l l e r p i d .C o m p u t e ( ) a n d
The MPU6050 module permanently records the current position forwarded to the motor driver with the following call:
of the robot. Its values are processed by the PID algorithm
in Arduino. The control sketch carries out the calculations for motorController.move(PIDout, MIN_ABS_SPEED);
controlling the motors. If the robot is in danger of tipping over  
in one direction, the resulting tilting moment is compensated In addition a check is carried out to determine whether the
by a corresponding compensation movement of the wheels. FIFO buffer of the MPU6050 is overflowing. This should not
The robot remains vertical even if it is pushed slightly. The happen during normal operation. If necessary, the buffer
corresponding sketch BalBot.ino is also included in the free size can be adapted.
download archive. The line:

Its code is divided into six parts: Serial.println(ypr[1] * 180/M_PI);  // actual tilt
 
1. Initially the libraries are loaded. If not included in the outputs the tilt angle. In the Arduino IDE serial plotter it
Arduino IDE by default, they can be got via Internet [2] can be tracked continuously. If regular, sinusoidal value
[3]. Then the motor connections are specified. The motors curves appear, that is a clear indication for the oscillation
can be operated both forward and reverse by means of EN of the control. In this case the control parameters need
(enable) and IN (input). The motor power is controlled by to be adjusted. In most cases it is helpful to reduce the
PWM. Kp value. Ideally, the line should only show small, irreg-
2. The values required for operating the MPU6050 are subse- ular signal deflections, such as those caused by random
quently defined. These are essentially the standard settings. disturbances (air movements or uneven floors). Figure 3
Details can be found in the IC datasheet [4]. shows the random compensating movements around the
3. Now the PID parameters are specified. They are of central rest position.
importance. The following three values define the control
behaviour: Kp (range 0-1000; default value 400), Kd (range Parameter optimization and adjustment
0-100; default value 30) and Ki ( range 0-500; default The optimization of the PID values could also be done by means
value 200). of a simulation for example with MATLAB. In the professional
4. These values must be adapted to the real conditions of the field, this procedure is standard for complex controllers.
respective hardware. Differences in mechanical construc- But with BalBot, the classic ’trial and error’ approach can also
tion (due to differences in motors, wheel sizes, etc.) can be used. Here, the individual parameters are gradually adjusted
be compensated here. Notes on the adjustment of these until the best possible control is achieved:
parameters can be found in the next section.
5. The required interfaces are now activated in the setup. The 1. First, the three parameters Kp, Ki and Kd are set to zero.
serial interface is only used to output debug information. 2. Next, Kp is slowly increased step by step. If Kp is too low,
This code can be omitted in the ’final release’. The MPU6050 the robot will tip over because the corrections are not fast
module is then started and checked for function - an error or large enough. If Kp is too high, the robot will perform
message is output if necessary. The specified offset values violent back and forth movements without reaching equilib-
can usually be accepted without modification, since the rium. Kp must be adjusted so that the robot moves back
gyroscope automatically calibrates itself. and forth only slightly.

www.elektormagazine.com May & June 2020 47


3. Upright standing with balancing movements is now achieved. If all three parameters are optimally set, the robot snaps into a
Often a certain tendency to oscillate still occurs: the robot nearly vertical position as soon as the controller’s catch range
quickly oscillates or quivers around the ideal equilibrium is reached. It then stands upright as if held by a ghost hand and
position. compensates for even larger disturbing influences with ease.
4. Now the Kd value is adjusted in a way to reduce the oscil- If no balance can be achieved, the motor connections may
lations. In the ideal case, the robot now remains in an have been mixed up. In this case, the robot does not acceler-
upright position almost motionless. If Kp and Kd are properly ate in the direction of the tilting moment, but in the opposite
adjusted, the robot will remain upright even if it is lightly direction. Figure 4 shows the finished robot in an upright,
bumped. self-balancing position.
5. Finally, the Ki parameter is set. Even with optimum Kp, Since setting the parameters by software is quite complicated,
a certain tendency to oscillate still occurs in the event of there is also a simpler variant. An Arduino has several analogue
major disturbances. It can even lose its balance. Ki is then inputs. Three potentiometers can be connected to these, allow-
ideally set when position stabilization occurs quickly after ing the values for P, I and D to be set directly. The software
a disturbance. only has to contain the query for the potentiometer values (see
  Listing: Potentiometers).
So the parameters can be
optimized during operation via
the potentiometers (see BalBot_
‘Potentiometers’ program listing Pots_BT.ino in the download).
The connection of the optional
void readPIDTuningValues()
potentiometers is already
{   int potKp = analogRead(A0);
considered in Figure 1.
    int potKi = analogRead(A1);
    int potKd = analogRead(A2);
    kp = map(potKp, 0, 1023, MIN_P, MAX_P) / 100.0;
Remote control by
    ki = map(potKi, 0, 1023, MIN_I, MAX_I) / 100.0;
smartphone
B u i l d i n g a s e l f- b a l a n c i n g
    kd = map(potKd, 0, 1023, MIN_D, MAX_D) / 100.0;
robot is an interesting learn-
}
ing challenge. If it all works,
this initially pleasing result is
no longer an exciting one in
the long run. A remote control
could change that. It would
‘Bluetooth’ program listing
allow BalBot to be moved
void readPIDTuningValues() wirelessly in all directions. Since
{   int potKp = analogRead(A0); nearly everyone (including the
    int potKi = analogRead(A1); electronics engineer) has a
    int potKd = analogRead(A2); smartphone with a Bluetooth
    kp = map(potKp, 0, 1023, MIN_P, MAX_P) / 100.0;  interface and many of them run
    ki = map(potKi, 0, 1023, MIN_I, MAX_I) / 100.0; 
under Android, such a smart-
phone can be used to control
    kd = map(potKd, 0, 1023, MIN_D, MAX_D) / 100.0; 
the robot.
}
All that is needed is to hook
 
up a Bluetooth module to the
content=blue.readString(); Arduino. An HC05/06 receiver,
  which is already included in
#if LOG_BT Figure 1, is well suited.
     Serial.print("content: ");Serial.print(content); To use it, the standard Bluetooth
     Serial.print(" - setpoint: "); Serial.print(setpoint); library of the Arduino IDE must
     Serial.print(" - rotation: "); Serial.println(rotate); be integrated and the sketch
#endif must be supplemented accord-
  ingly (Bluetooth listing).
if(content[0]==’F’)
This extension is also already
       // forward
included in the sketch BalBot_
else if(content[0]==’B’)
Pots_BT.ino. The smartphone
       // backward
only needs the app „Arduino
else if(content[0]==’L’) Bluetooth“ from Circuit Magic.
       // left The app can be downloaded
else if(content[0]==’R’) for free from the Playstore [5].
       // right After installation and connection
with the HC05/06 module the

48 May & June 2020 www.elektormagazine.com


app sends the necessary control commands to the Arduino.
Figure 5 shows the user interface of the app. The app is
controlled using the arrow keys on the left side of the screen.

Conclusion & Outlook


The robot presented here can be assembled with a minimum
of effort. Besides the drive motors only an Arduino, a motor
driver and an acceleration/gyroscope module are required. The
adjustment of the control parameters is considerably simpli-
fied by additional potentiometers. BalBot can even be moved
remotely within your own four walls via Bluetooth.

Figure 5: Android app for controlling BalBot via Bluetooth.

A further improvement of balance and handling, especially in


remote-controlled operation, could be achieved by so-called
rotary encoders. This allows the speed of rotation of the wheels
to be recorded. This information can be used to further improve
stability when driving forwards and backwards. In practice,
the remote-controlled BalBot occasionally loses its balance if
only the values of the MPU6050 are available. Unfortunately,
this sensor can only measure acceleration and rotation, but
not the speed directly.
Another alternative is to use stepper motors. Counting the
steps provides information similar to that obtained by encod-
ers. Besides replacing the motors, the L298 must of course
be replaced by suitable stepper drivers (such as the DRV8825
driver).
200074-02

Figure 4: BalBot in action.

Web Links
[1] Article support page: www.elektormagazine.com/200074-02
[2] PID_v1.h: https://github.com/br3ttb/Arduino-PID-Library/blob/master/PID_v1.h
[3] MPU6050_6Axis_MotionApps20.h: https://bit.ly/37T7T1c
[4] MPU6050 datasheet: www.invensense.com/products/motion-tracking/6-axis/mpu-6050/
[5] ‘Arduino Bluetooth‘ app: https://play.google.com/store/apps/details?id=com.circuitmagic.arduinobluetooth&hl=en

www.elektormagazine.com May & June 2020 49


Starting Out in
Electronics (3)
Easier than imagined!

By Eric Bogers (Elektor Netherlands)

In the previous episode we got acquainted with Ohm’s Law and did some elementary calculations. Now it
gets a bit more complicated — but no fear: we don’t need higher mathematics...

First a small update to the previous reasoning is rickety but it does make Parallel connection of resistors
episode. There, we mentioned that a some sense of what is happening. Resistors are not only connected in series
decimal prefix is often written instead Now let’s see exactly what happens. (’sequentially’) but also in parallel (’side
of the decimal point: 8.2 kΩ becomes Thanks to Ohm’s Law, we know that the by side’), as outlined in Figure 2. First
8kΩ2 and 5.6 nF becomes 5nF6. There voltage U across the series connection eliminate R2 for a moment; then we
we noted casually that the µ (’micro’ or of R1 and R2 (which we call R) equals know that a certain current will flow
10-6) is at least tricky to find on our US/   through R1. Now we add R2; a certain
UK keyboards. In fact the key combi- U=RI current will flow through it as well.
nation is ALT+0181, but that is clumsy.   Therefore, when connected in parallel,
That’s why instead of the µ, a ’u’ is often Now resistors are not mysterious compo- the total current increases; and since the
written and then we get: 4.7 µF = 4.7 uF nents — no power is lost in them. So the voltage across the resistors remains the
= 4uF7 or even 4u7. current I in the series circuit is equal same, that means the total resistance
to the current leaving the series circuit, has become smaller!
Series connection of resistors and so both resistors pass the same Looking at Figure 2 again, two things
Over to business as usual. What happens current. Each of the resistors drops a are clear: both resistors R1 and R2
when we connect two resistors in series, certain voltage (which in turn follows have the same voltage U across them.
as outlined in Figure 1? If we consider a from Ohm’s Law), and because resis- Consequently, the sum of the currents
resistor as a component that impedes the tors are purely passive components, no through the individual resistors is equal
current flow, we could reason as follows: voltage is added along the way (and no to the total current I: we are dealing with
the current is obstructed by R1, and the voltage disappears either), so the sum purely passive components, so no current
small amount of current that manages of the two partial voltages U1 and U2 is disappears or gets added along the way.
to pass that resistor is obstructed again equal to the total voltage U. Armed with If we call the total resistance of the paral-
by R2. So it is obvious that the total that knowledge, we can write: lel circuit R again, we get:
resistance increases when connecting    
resistors in series. Yes we know, this U1 = R1 I U=RI
 
U2 = R2 I
 
And since U1 + U2 = U:
 
U = (R1 I) + (R2 I) = (R1 + R2) I
 
And it follows that the total resistance R
equals the sum of resistors R1 and R2.
Okay so you had guessed that and it’s
obvious too, but of course it’s nice to
know for sure.
We leave it up to the reader to check the
above by means of a numerical example
(e.g. take a battery voltage of 15 V,
Figure 1: Series connection of two resistors. R1 = 10 Ω and R2 = 20 Ω). Figure 2: Parallel connection of two resistors.

50 May & June 2020 www.elektormagazine.com


Now we apply Ohm’s Law to the individ-
ual resistors:
 
U = R1 I1 I1 = U / R1
 
U = R2 I2 I2 = U / R2
 
With I1 + I2 = I, we write
 
I = (U / R1) + (U / R2) = U / R
 
and from that:
 
1 / R = (1 / R1) + (1 / R2) Figure 3: Simple mixed circuit. Figure 4: The H-circuit, a dreaded occurence in
  exams.
Rearranging:
 
R = 1 / [(1 / R1) + (1 / R2)]
  • With series connected resistors, the physics) something is only obvious when
We leave it up to the attentive reader total resistance is always greater it is irrefutable proven. And physicist
to check this outcome by means of a than the largest of the series Gustav Kirchhoff did that back in 1845.
numerical example. connected resistors; Kirchhoff’s First Law states that the sum
• with parallel connected resistors, the of the currents in a node equals the sum
Mixed circuit total resistance is always smaller of the currents from that same node.
In daily electronics practice we are not than the smallest of the parallel
only dealing with ’pure’ series and paral- connected resistors. The H-circuit - a forward view
lel circuits, but also with ’mixed circuits’   Armed with the knowledge we have now
such as those of Figure 3. There we see a For example, if we have a series connec- acquired, we can calculate simple mixed
series connection of a single resistor (R1) tion of a very large and a very small circuits such as the ones from Figure 3
with a parallel connection of two resis- resistor (say 100 kΩ and 10 Ω), then without many problems. But take a look
tors (R2||R3). (Note: a parallel circuit is in everyday electronics practice we at Figure 4 - a mixed circuit of the trick-
often indicated by two parallel bars ||). don’t calculate that exactly, but just ier kind. In this so-called H-circuit, we
Let’s look at a numerical example here: say that the total resistance equals the cannot find combinations that we can
R1 = 10 Ω, R2 = 20 Ω and R3 = 30 Ω. largest resistance, so 100 kΩ. And with treat separately as series or parallel
Although it is possible to write down a parallel connection of the same resis- circuits. How can we do that? How do
single relationship for the total resis- tors the same holds: we save ourselves we deal with such a thing?
tance, such an approach is likely to incur the trouble of calculation and say that Think about this; in the next episode
mistakes and arithmetical errors. It is the total resistance equals the small- we will come back to this (keyword:
better to calculate the total resistor in est resistance, so 10 Ω. The difference star-delta transformation or Y-Delta
two steps: first the parallel circuit and with the actual values is so small that transformation). And then we will also
then the series circuit. For the parallel we shouldn’t have to worry about that. deal with alternating currents and
circuit of R2 and R3 we write: And another remark close to the end: voltages.
  above we’ve limited ourselves to series 200106-02
1 / Rparallel = (1 / R2) + (1 / R3) and parallel connection of two resistors
  each, but mutatis mutandis everything
Entering the example value yields: we’ve reasoned and calculated also holds
  for series and parallel connection of more
1 / Rparallel = (1 / 20 Ω) + (1 / 30 Ω) = than two resistors:
(3 / 60 Ω) + (2 / 60 Ω) = 5 / 60 Ω
  • series connecton of n resistors:
In reverse: Rparallel = 60 Ω / 5 = 12 Ω Rseries = R1 + R2 + ... + Rn

This resistor is connected in series with • parallel connectioon of n resistors:


R1; for the total resistance R of this 1 / Rparallel =
mixed circuit, we arrive at R = 10 Ω + (1 / R1) + (1 / R2) + ... (1 / Rn)
12 Ω = 22 Ω.  
Back to Figure 2. As a result of it we
A few remarks noticed that the sum of the currents I1
As you can now easily check for yourself, and I2 equals the total current I. That
the following rules of thumb apply for seems very obvious, but in physics (and
guesstimates and quick estimates: electronics is no different than applied

www.elektormagazine.com May & June 2020 51


Small Circuits Revival
Capita Selecta from the Elektor Project Suggestions Box

By Eric Bogers (Elektor Netherlands)

Small circuits not using SMD components or special tools, that can be built on stripboard and invite
experimentation and improvisation – these are frequently a springboard to a career in electronics. Here we
again present a selection from the Suggestion Box of your favourite magazine.

Idea: Michael A. Shustov (Russia) and Andrey M. Shustov (Germany) be restored; after a short time C1 is charged again via D1 and
Energy-efficient Light-sensitive Relay the circuit is armed once more.
In the first episode of this series (Elektor January & February Transistor T3 does actually the same thing as the pushbut-
2020) we described a few variations on the subject of tons: in the dark this light-sensitive transistor is off and the
‘energy-efficient relay’ from the father & son team Shustov. circuit is in the rest state. When light strikes the transistor (for
These are actually also variations of the well-known stairwell example from a torch) it will switch on and pull the base of T1
switch circuit. The Shustovs haven’t been sitting idle: Figure 1 to ground — and then the circuit behaves in exactly the same
shows a version that has been expanded with a light-sensitive way as after pressing one of the buttons.
transistor, so that the lamp is not only turned on by pressing This method makes the circuit appropriate for application in
one of the buttons SB1 through SBn, but can also be turned a cellar, for example, where it is normally dark (!) — you do
on from a distance using, for example, a torch. not have to search around for the light switch and only have
If we forget about T3 for the moment, then the circuit operates to strike a match or something...
exactly as described in the first episode. In the rest state the  
series-connected pushbuttons SB1 through SBn are all closed
(for the sake of simplicity only one is drawn). A small current
can flow through the lamp via R1 and LED1 to ground — the
LED will light up to indicate that the circuit is ‘armed’. At the
same time, capacitor C1 is charged via D1. By the way, the
current through the lamp is not high enough for it to light up.
(And it will be clear that this has to be an incandescent lamp).
As soon as a button is pushed there is no longer any current
through the lamp and the base of transistor T1 is pulled to
ground (via R3, R2, R1 and LED1). The transistor will start to
conduct and C1 will discharge via R4. As a consequence, the
voltage across R4 becomes high enough for T2 to turn on so
that enough current will flow through the lamp for it to light
up (of course once the pushbutton is released).
This state is stable for as long as the voltage across R4 is high
enough for T2 to continue conducting. Once capacitor C1 has
discharged sufficiently so that T2 turns off, the initial state will

1
LA1
D1 1N4004

SB1-SBn
R1
T1 Idea: Joseph Kreutz (France)
R2 R3 BC557
Preamplifier for Crystal Pickup Elements
2k

10k 300k

LED1 T2 You will know them — the so-called ‘stereo consoles’ from
2N7075
the seventies of the previous century? These large wooden
GB1 T3
12V L-53P3C R4 monsters with on one side a radio attached to an amplifier
50k C1
1000µ (no transistors, only tubes) with bulky mechanical selector
16V
pushbuttons and large volume and tuning knobs on either side
of a beautiful ‘multi-band’ tuning scale. And on the other side
200110-51 KD
a gramophone for 33, 45, and 78 rpm records?
That gramophone… Belt drive was a rarity, direct drive still

52 May & June 2020 www.elektormagazine.com


And this is exactly what the small circuit of Figure 3 does:
2 VCC
it is a small external watchdog that, if it doesn’t receive any
trigger pulses from the microcontroller for about 10 seconds,
R1
C5 C6 will turn off the power supply voltage for about 5 seconds and

390k
100n 10µ
then turn it on again.
The circuit is built around a ‘good old’ 555 — one of the oldest
R2
C1
1M8
2µ2 workhorses in electronics and still a favourite component when
C2 U1
some timing is involved.
3 7 TL071
6
C7 Audio out It is not difficult to understand the operation of the circuit:
100n
Crystal
2
5 10µ
the regular trigger pulses from the microcontroller (note: the
1
microphone 4 R5
C4
software that is running on that controller has to generate

1M
10p
these, but that will not be a problem for any slightly accom-
plished programmer) will turn on transistor T2 each time, which
R3 R4 R6 results in the discharge of timing capacitor C4 of the 555. The
2M2

47k

22k
555 is configured as an astable multivibrator.
C3
100n As a result the voltage across the capacitor cannot normally
reach the trigger threshold necessary to activate the 555. The
200110-52 KD

3 V+
had to be invented. The drive used a rubber wheel between
the motor shaft and the inner rim of the turntable. And of R3 4 8 R4

270k

47k
C2
RESET V+
100n
course this gramophone was equipped with a crystal element 7
DIS
T1
RFR9024
(sometimes called a ceramic element). IC1
R2 NE555

820k
Such an element generated a relatively high output voltage, OUT 3
T3 OUT
6
but had to be loaded with a high impedance. The latter was 2
THR BS170

Trigger
not a problem for the valve equipment of the time, of course. T2
Bs170 CV GND GND
Trigger
However, it is a problem now, because the ‘phono’ input of a 5 1
D1
modern amplifier (assuming that it still has one, in this CD era) C1
100n
1N4148
C4 C3
R5 R1
27k
10k

10µ 10n
has a normalized input impedance of 47 kΩ and that is much
too low with all its consequences; furthermore, all modern
200110-53 KD
phono amplifiers are designed for signal levels in the order of
millivolts. This is guaranteed not to work well.
If, in spite of all this, you would like to experiment with old
‘crystal gramophones’, we need a preamplifier/impedance output (pin 3) of the 555 remains high and the power supply
converter. Fortunately such a thing is easily realised, as voltage to the microcontroller is turned on via T3 and T1.
Figure 2 demonstrates. The heart of the circuit is a high-im- However, when the trigger pulses remain absent for more than
pedance FET opamp type LT071. With resistors R1 through 10 seconds, the voltage across C4 will be high enough for the
R3 the input impedance is matched as good as possible to the 555 to toggle: the output becomes low and T1 will turn off via
microphone or element. The opamp is used to build a standard, T3 and the power to the microcontroller is cut off. After about
non-inverting amplifier with a bandwidth that is limited by 5 seconds the 555 will switch back and the power supply is
capacitors C3 and C4 from about 33 Hz to a little less than switched back on.
16 kHz. The gain is about 21 times and is suitable for connect- 200110-02
ing to a CD input of a modern amplifier.
There is not much more to say about this simple circuit, except
that it is not only suitable for crystal pick-up elements, but
also for the crystal microphones that were often supplied with
the tape recorders of that era (and is already indicated in the
schematic).

 
Idea: Wolfgang Borst (Germany)
External Watchdog for Microcontroller Systems
A microcontroller that runs 24 hours per day, 7 days per week,
can latch up for whatever reason (note: can, it fortunately
only happens rarely). In these cases, the normal reset signal
generated by the internal watchdog may not be sufficient to
4 sale @ www.elektor.com
escape from this situation. On these rare occasions only one ªElectronic Circuits For All
thing will do: turn off the power supply voltage completely and www.elektor.com/electronic-circuits-for-all
then turn it back on.

www.elektormagazine.com May & June 2020 53


Tamper-Evident Box
Send data securely through postal services
By Luka Matić (Croatia)

In secure communication systems based on one-time pads


(OTPs), messages are encrypted and decoded with a
random key. To make this work, both the sender —
usually called Alice — and the receiver — better
known as Bob — need to use the same key.
Alice generates the key, but how can she
send it to Bob in a secure way? It is this
chicken-and-egg problem that the project
described in this article is trying to solve.

Quick Specifications
• Open source design
without hidden tricks
• Capacitive box-opened detection
• Incident light
box-opened detection This project is a (logical) sequel to my ing a tamper-proof device, but then
• Travel time verification TRNG [1] and OTP Crypto Shield [2] and learned that securely erasing data from
• Temperature attack detection tries to solve the problem of securely a flash-memory-based device like a solid-
• Infrared communication exchanging one-time pad (OTP) keys state drive (SSD) or SD card is practi-
• Reusable stored on, for instance, an SD card. cally impossible [3]. Furthermore, even
I started out with the idea of design- SRAM memory exhibits some parasitic

54 May & June 2020 www.elektormagazine.com


burn-in effects, allowing to recover the Bob simply discards the SD card and will
data it contained [4]. With this in mind I not use the potentially unsafe OTP key project decoder
decided not to build a box that’s tamper- for secure communications with Alice. Secure communication
proof, but one that will indicate it was If the box is opened without first being
encryption
tampered with. disarmed using the challenge string,
or if it is tampered with in some other IR communication AVR
Principle of operation way, it will securely delete the challenge-
entry level
Alice stores a freshly generated OTP and-response strings from its memory.
Æ intermediate level
key on a microSD card and puts it in Eavesdropping Eve or malicious Mallory
expert level
the tamper-evident box. She closes the may intercept the box to read and copy
box and arms it by storing a challenge- the SD card and forward the box to Bob,
and-response string in it by means of but they can’t re-arm the box with the
3 hours approx.
a non-contact (infrared) link. She then same challenge-and-response sequences
mails the box to Bob. When he receives as only Alice knows them, and so Bob
it, he asks Alice for the challenge string. will eventually find out.
He can use any ’non-secured’ channel for (SMD) soldering iron,
this — e.g. phone or email —, as only Hardware description AVR programmer
Alice knows this string and Bob has the Refer to Figure 1 for the complete
box. Using the optical link, Bob unlocks schematics of the tamper-evident box.
the box by entering the challenge string. Microcontroller IC1 is the heart of the
€50 approx.
The box will respond with either the device. Every two seconds it wakes up
response string or with a warning about from power-save mode for less than
a potential tampering event. Only Alice 50 ms to check several parameters. If
can confirm the validity of the response these parameters indicate a tamper-
string. If the response string is invalid or ing event, the MCU securely erases
if the box gave a tamper event warning, (zeroizes) its SRAM contents, something

VCC VCC

R2
C1 100k
100n
L1
10µH 7 P3 P2
D1 1k 25k R3
20 VCC 23 E A E A L2
AVCC PC0(ADC0) 1k
1N4148 S S 220µH
C6 R13
100n C10 C1X 30x30mm
1M

10n plane
D4 R30
16 C14 C15 R4
1k5 PB2(SS/OC1B) P1 P4
D2

10k
E 1k A E 25k A
1N4148 T4 T3 C18 24
PC1(ADC1) 120p 10n
VREF1 R21 10n
IC1 R14 1N4148 S S
10M

R11 C11
ATmega328P
1M

C16 10n VCC


SFH- SFH-
33k

1n IC3 C2X 30x30mm


300-3/4 300-3/4 5 plane
D5 MAX9914EXK+T D6 Vbat
1 S1
VREF2 BAT54
28 R16
LM285D-1.2*

4 26
R12 PC5(ADC5/SCL) PC3(ADC3) 10k
C17
C7 3 C8
10k

25 D3 1N4148
1n PC2(ADC2) 10µ
2 R5 PB0-CLKO/2C 100n 10V
14
1M PB0(ICP) tantal
R23 R20 27
R6 PC4(ADC4/SDA) 22k
R29 VCC
* not LM385 R15 R10
10k
100k

10k

10k
10k

C12 C13 Vbat


1M

10n 10n C9 R17 K3


10
10k

10n
21 9 BAT1
AREF TXD-IR
R25 4 VBAT-MEASURE/2.3B 8
PD2(INT0)
10k 5 7
PD3(INT1) PD3 CR2032
9 6 6
PB6(XTAL1/TOSC1) PD4(XCK/T0) PD4 HOLDER
Vbat X1 32.768kHz 18 5
VCC Vbat PB4(MISO)
R24 10 4
12 MISO
T1 1M PB7(XTAL2/TOSC2) PD6(AIN0)
13 3
BC857C 6 PD7(AIN1) SCK
3 C3 C4 R9 R19 R18 2
1 2 5 MOSI
330

100

R22
100

S3 22p 22p
4 15 1
33k PB1(OC1A)
IC2 1 R7 K2
start R28 PD5(T1) 11 LED2 LED1
3 4 2M2 DM3AT-SF-PEJM5
MAX9915
100k

EXT+T 2 8
VCC T2 7 DAT1
BC857C 6 DAT0
R27 10
VSS DET-A
220k LED3 VCC 5
2 IrDa link
PD0(RXD) CLK
100k

R1 9600 bps TSAL-6200 4 9


3 1-LED (Tx & Rx) VDD DET-B
R26 1 PD1(TXD) 3
C2 CMD
2
330k

PC6(/RESET) R8
10µ K1 CD/DAT3
S2 1
22k

10V tantal RESET 2 1


3 4 DAT2
17 4 3
C5 PB3(MOSI/OC2)
100n 6 5 14 13 12 11
1 2 ISP microSD card connector
PB5(SCK) 19 push-push type
GND GND
180445-006-94 KD
8 22

Figure 1. The tamper-evident box uses phototransistors and open-plate capacitors for detecting tampering.

www.elektormagazine.com May & June 2020 55


centimetre, but this is more than enough. spots for placing probes or interfering
K1
The circuit is powered by one CR2032 otherwise without removing the PCB. The
MICRO-SD-HIROSE battery with a nominal voltage of 3 V. open-plate capacitor on the bottom side
8
DAT1 It will last for more than one month will detect this.
7
6 DAT0
10 (Figure 3), which should be enough even
VSS DET-A
5
CLK
for the slowest snailmail carriers. A fresh The IR communications adapter
CX 4 9
30 x 30 mm 3 VDD DET-B battery typically starts at 3.3 V, and the An infrared (IR) link is available for
plane CMD
2
CD/DAT3
circuit will work with a supply voltage as communicating with the hermetically
1
DAT2 low as 2.1 V. This is made possible by sealed tamper-evident box. This link is
14 13 12 11 the low-dropout (LDO) voltage regula- not particularly fast (9,600 baud) and has
tor built around IC2, which produces a a rather short-range (1 cm), but it works
stable 2.0 V at VCC. without the need to open the box. The
D5 provides a precise voltage refer- adapter (Figure 4 and Figure 5) that
ence for the MCU’s analogue-to-digi- makes this possible consists of a small
Figure 2. The open-plate capacitors C1x and
tal converter (ADC). The LM285 is an microcontroller, an ATtiny45, equipped
C2x are 30 x 30 mm plates of PCB material
with a copper plane on one side. A microSD extended-temperature-range variant with an IR transceiver almost identical
card connector can be mounted too. of the LM385, allowing the circuit to to the one of the box. The circuits differ
operate safely with sufficient precision slightly due to the low-power constraints
from −20 °C up to +60 °C i.e. tempera- for the box that do not apply to the IR
tures that may be experienced during its adapter.
papermail voyage. The user side of the adapter has a serial
The MCU is clocked from its internal port. Since entering the challenge-and-
1-MHz RC-oscillator. To keep energy response codes is a security-critical
consumption to a minimum, this clock procedure, the IR adapter can connect to
is only turned on at two-second inter- a computer in various ways, e.g. through
vals for a duration of about 50 ms. The a USB-to-serial converter (cable), over
low-power 32.768 kHz clock based on a ’real’ RS-232 port, and even over
watch crystal X1 runs continuously and Ethernet if you add a WIZnet WIZ107
times these wake-up moments. It is Ethernet-to-serial adapter. These options
also used to tune the MCU’s UART clock allow dedicating a cheap notebook PC
on each wake-up, and it provides the that never ever connects to the Internet
Figure 3. To save power the box wakes up
timebase for precisely measuring the to the box.
only every two seconds for about 50 ms. The
voltage regulator is activated (top trace) to
duration of the box’s journey.
measure vital tamper parameters. The bottom R3, L2 and C14 filter the 1-MHz square Adjusting the capacitive
trace shows the current consumption. wave derived from the MCU clock output detectors
on PB0, to obtain a sinewave that can For proper operation of the capacitive
be used to accurately measure the C1x tamper detection the trimpots P1, P2, P3
and C2x capacitances. Both peak and and P4 need to be adjusted. Power up
that is not possible with flash memory mean values are measured, and the the box (LED2 will blink once, followed
or EEPROM. ratios of the AC voltage on C1x and C2x by LED1) and place the IR adapter’s IR
Opening of the box is detected in two with respect to the AC voltage on C14 LED in front of LED3 of the box at less
ways: get calculated. A significant change in than 1 cm. Connect the IR adapter to
one of these ratios indicates tampering. a computer running a serial terminal
• Change in capacitance of the box (it LED1 and LED2 indicate various states of (9600n81). After typing ’U’ (0x55) in
must be a metal box). C1x and C2x the box. For instance, LED1 blinks when a the terminal, you will see this data block
(Figure 2) are open-plate capaci- correct challenge code was entered, and arrive every two seconds:
tors ’protecting’ the SD card placed LED2 blinks when it was incorrect. They
in between them. Their other plate is both blink once after power-up. LED1 Box unlocked. Status-1. Define
the metal (!) enclosure of the box. A flashes once on every MCU wake-up as it challenge string.
change in their capacitance indicates is used to help the LDO output to quickly Capacitor Cx1 voltage ratio: 0.703
tampering. reach 2 V. If LED2 blinks once on every Capacitor Cx2 voltage ratio: 0.703
• Light detection. The box is sealed MCU wake-up, then a tamper event was
Phototransistor voltage [V]: 0.181
and 100% lightproof; inside the box detected.
Box temperature [degC]: +22
it’s completely dark. Phototransistors Switch S1 is the box’s power switch, and
Battery voltage [V]: 2.900
T3 and T4 detect infrared and visible S2 is the MCU’s reset button. Pushbutton
light as soon as the box is opened. S3 allows to boot the circuit in case the  
battery voltage is a bit on the low side. For maximum measurement sensitiv-
For entering the challenge-and-response Note that the PCB has components on ity trimmers P1 through P4 have to be
codes an infrared IrDA-like link is used. two sides. That’s in order to hide a part adjusted in such a way that the combined
LED3 ensures bidirectional communica- of the circuit from a malicious investiga- resistance [P2+P3] equals the reactance
tions. The maximum range is around one tor, making it more difficult to find good C1x, and the sum [P1+P4] equals

56 May & June 2020 www.elektormagazine.com


reactance C2x. This sounds complicated,
but the status data contains voltage K4 D3 +5V IC3 +3V3 +5V
USB-MICRO MBR120 LD1117AS33
IC1
ratios to help you here. They must be 2
VBUS 1 3
close to 1/√2, i.e. 0.707. Because the D- 2 ADJ 16
D+ 3 C8 C9 1 C10 C1 1
C1+
VCC
LED3
box itself acts as a capacitor plate for GND ID
4 100n 100µ/16V 1µ 10µ C6
C4
MAX232ECWE
the open-plate capacitors C1x and C2x, 5
10V 1µ 3 2

C1- V+
the voltage ratios must be correct with +5V +5V
R1
4
C2+ V-
6
C7
the box’s lid in place. Use P2 and P4 for C5

680
C3 1µ
100n 1µ
coarse adjustments and P1 and P3 for 5
C2-
RS232
K1
fine tuning. D1
1N4148
2 1 11
T1IN T1OUT
14 1
TXD
4 3 12 7 2
4k7 R1OUT T2OUT GND
6 5 10 13 3
R4 IC2 R7
R2 T2IN R1IN RXD
Temperature measurements ATtiny 8

100k
ISP 9
R2OUT GND R2IN K2

1k5
45-20SU 8 +3V3
The MCU has a built-in temperature R3 (RESET)PB5
1 15

sensor. Its precision is low — some 2M2 (MISO)PB1 6


5
T1 (MOSI)PB0 7 R8
±5°C — but good enough to detect BC857C (SCK)PB2 K3
WIZ107SR
+5V

4k7
abnormal temperatures and to log the LED1 TSAL6200
3
D2 2
VCC VCC
1
IrDa link MBR120 4 3
(XTAL2)PB4 S1
approximate minimum and maximum 9600 bps
1-LED (Tx & Rx) 2 (XTAL1)PB3 RESET K5 6
RESET
FAC_RST
RXD
RTS
5
6
8 7
temperatures during the box’s journey. R6 R5 GND 5 HW_TRIG TXD

5V FTDI cable
10 9
1 3 4 NC CTS
680

The temperature is measured by reading 22k


4
3
12
GND GND
11
2 4
ADC channel 8, which is the MCU’s inter- LED2
C2
100n
2
1
nal thermometer. Although designed to
work with the MCU’s internal voltage 180445-004-94 KD

reference (1.1 V and not very stable),


if we throw in some math (an affine
Figure 4. The IR communication adapter provides an interface between the hermetically-sealed
function), an external voltage reference
tamper-evident box and a computer.
(D5) can be used to improve things. This
way much better precision than stated in
the MCU’s datasheet can be obtained. If
needed, the slope of the affine function something like this: except in states 3 and 5. In these states
can be modified inside the program, in data transmissions stop after 60 seconds
the function measure_signals(). Box unlocked. Status-1. Define to save power.
The temperature sensor needs calibrat- challenge string.  
ing to make it useful. The ‘TP’ command Capacitor Cx1 voltage ratio: 0.710 Status-1
is available for this, to be sent from the Capacitor Cx2 voltage ratio: 0.704 Status-1 is the initial state of the box
terminal. Its syntax is ‘TPsxx’ where ‘s’ after power-up, and the device waits for
Phototransistor voltage [V]: 0.181
is the sign ‘+’ or ‘−’ (the sign is manda- a challenge string to arrive on its infra-
Box temperature [degC]: +25
tory), and ‘xx’ is the offset (as a 2-digit red receiver. Alice enters the challenge
Battery voltage [V]:       3.354
value, i.e. ’00’ to ‘99’). As an example, string in the terminal (up to 65 charac-
if the ‘Box temperature’ value is given   ters, longer strings are truncated). The
as +40°C when the ambient tempera- The box outputs these blocks of data box will now enter Status-2.
ture really is +25°C, then you should every two seconds on its infrared port, Important note: all strings, including
send ‘TP−15’ from the terminal. Sending
‘TP+00’ will set the offset back to zero.
The offset is stored in the MCU’s inter-
nal EEPROM.

User manual for spies


Alice creates a file of random numbers
with her TRNG and copies it to a never-
used SD card. She inserts a new battery
in the box and switches it on with S1.
Because the battery is fresh, it will not
be necessary to press S3 to make the
device boot. Then she puts the SD card
into the socket and closes the box. With
the IR adapter in front of the IR LED of
the box she first sends the character ‘U’
(0x55) from her terminal. This allows the
MCU of the IR adapter to calibrate its
UART clock. The terminal will start receiv-
ing messages from the box, displaying Figure 5. The IR communication adapter with the (optional) Ethernet module mounted.

www.elektormagazine.com May & June 2020 57


multi-character commands, must be be entered. The voltage ratios of Cx1 Box locked. Status-3. Enter
copy-pasted into the terminal and not and Cx2 and the phototransistor voltage challenge string to unlock.
typed character by character! are stored in the MCU’s SRAM. If these Capacitor Cx1 voltage ratio: 0.710
Box unlocked. Status-2. Define voltages change too much during the Capacitor Cx2 voltage ratio: 0.704
response string. voyage then tamper alert is given. Phototransistor voltage [V]: 0.181
Capacitor Cx1 voltage ratio: 0.710 Alice enters the response string (up to
Box temperature [degC]:      +25
Capacitor Cx2 voltage ratio: 0.704 65 characters) to arm and lock the box
Battery voltage [V]:       3.354
and make it enter Status-3. The travel-  
Phototransistor voltage [V]: 0.181
time clock is started too. Alice writes down Status-3
Box temperature [degC]:      +25
the date and exact time of day along Both the challenge-and-response strings
Battery voltage [V]:       3.354
with the challenge and response strings have been entered and the box is armed
  and hides it all securely (in her head, if and locked. Any tampering with it or
Status-2 possible). It will be used for verification entering an incorrect challenge string
The box waits for a response string to later. She then mails the box to Bob. five times will trigger the zeroization

component list

58 May & June 2020 www.elektormagazine.com


sequence. The box remains in Status-3
during its travel with the papermail
carrier.

The SRAM buffers containing the


challenge and response strings are
complemented (bitwise-inverted) every
two seconds. This way, the parasitic
burn-in of SRAM cells [4] is prevented,
because each bit will spend and equal
amount of time in both the ‘0’ and ‘1’
state.

At Bob’s place
After a long and perilous journey,
the box (hopefully) arrives at Bob’s
place. He connects his IR adapter to
a computer, places it in front of the Figure 6. The fully assembled board with open-plate capacitors installed on both sides.
box’s IR LED, and presses the Reset
button on the adapter. This will produce
a three-second pulse on the infrared port
to tell the box to activate its infrared
port and start communicating on it. After
three seconds Bob proceeds by sending
a single character ‘U’ to calibrate the IR
adapter’s UART, and the terminal starts
displaying data:

Box locked. Status-3. Enter


challenge string to unlock.
Capacitor Cx1 voltage ratio: 0.703
Capacitor Cx2 voltage ratio: 0.711
Phototransistor voltage [V]: 0.175
Box temperature [degC]:      +23
Battery voltage [V]:       2.752

 
As we can see, the battery voltage has
decreased, but there are no visible signs
Figure 7. The bottom side of the board/ PCB is populated with SMD components and through-hole
of tampering as the Cx voltage ratios
transistor T4 that looks like an LED. Capacitor C1x is mounted over the microSD card connector.
and the phototransistor voltage values
have not changed much. Bob calls Alice
and asks her for the challenge string. He
enters it in his terminal, and, if every- Status-4 Box zeroized. Status-5. Tampering,
thing is fine, he will see: Bob immediately writes down the current wrong password, or low battery!
time and date and calls Alice again to Capacitor Cx1 voltage ratio: 0.712
Box unlocked. Status-4. Challenge verify the response string. If Alice Capacitor Cx2 voltage ratio: 0.713
string correct!! accepts it, she will now give Bob the Phototransistor voltage [V]: 0.179
Capacitor Cx1 voltage exact time and date that she wrote down Box temperature [degC]:      +12
ratio:      0.703 when she locked the box. This allows Bob
Battery voltage [V]:       2.793
to calculate the theoretical travel time  
Capacitor Cx2 voltage ratio: 0.711
and compare it to the time measured Status-5
Phototransistor voltage [V]: 0.178
by the box. If the two match, then Bob The zeroization sequence was executed
Box temperature [degC]:      +24
is allowed to use the OTP key stored on due to the detection of a tamper event
Battery voltage [V]:       2.752 the microSD card to encrypt and decrypt or after entering five invalid challenge
Min temperature [degC]:      -2 his secure communications with Alice. In strings. The tamper-check voltages are
Max temperature [degC]:      +31 case of being tampered with along the no longer updated, allowing the holder
Travel time [s]:       502,164 way, the box will erase the part of the of the box to see the last recorded state
Response: SRAM containing the codes and the travel before tampering was detected.
Trust no one 01a2g23w46e57f80g12r3 timer. In this case the box will output The zeroization sequence is executed in
e34fv245hasdvfr4. something like this: one of the following cases:

www.elektormagazine.com May & June 2020 59


• After entering an incorrect challenge Status-6 silicon die. This can do as much harm
string five times; After receiving the ‘DE’ command the as a software Trojan or even more. It
• The actual capacitor voltage ratio box will transmit details about the cause poses a great danger for today’s MCUs
differs too much from the recorded of the zeroization. with their CPU, SRAM, EEPROM and flash
value; The data displayed in states 5 or 6 memory integrated on one silicon die,
• The actual phototransistor voltage doesn’t have to be valid as it depends and that are programmable with a low
differs too much from the recorded on what Mallory has done to the box. She voltage (3 to 5 V). Basically, there are
value; may have reset it and entered challenge two types:
• Battery voltage too low (below and response strings before forwarding
2.1 V); the box to Bob in Status-3. However, 1. General-purpose hardware Trojans
• Temperature out of bounds (below even if she somehow manages to enter Mallory can plant a hardware Trojan in
−20°C or above +60°C). the correct strings, she will have to spoof the MCU, e.g. to periodically copy the
the travel timer as well, and this will be MCU’s SRAM and registers to some secret
To avoid stray light from triggering much more difficult. part of flash memory. Regardless of the
tamper event 3, make sure the box is MCU’s application, a ’frozen’ snapshot
hermetically sealed. Apply some black Back to Status-1 of RAM will always be useful for her
sealant paste around LED3 on the inside The command ‘RE’ can be used to reset and Eve. With such a Trojan in place
of the box and seal the edges of the the box to Status-1 without opening it. Mallory can easily read the challenge
box with sticky black electrical isolation Pressing the S2 reset button inside the and response strings defined by Alice.
tape. Test it by exposing the closed box box will do the same. However, spoofing the travel timer will
(in Status-3) to direct strong sunlight. be a little bit more difficult.
Now Bob can enter the ‘DE’ command A word about hardware Trojans
to see what has caused the zeroization: Since most people usually only worry 2. Application-specific hardware
about software malware and Trojans Trojans
Box zeroized. Status-6. Tampering attacking their computers, a few words To plant this kind of hardware Trojan,
status display! about hardware Trojans is in place here. Mallory needs to have knowledge about
Capacitor Cx1 voltage ratio: 0.683 A simple system with a single MCU that the MCU’s firmware first. Then she rigs
Capacitor Cx2 voltage ratio: 0.656 is never connected to the Internet is the MCU with a circuit capable of recog-
100% secure against typical malware nizing the firmware that Alice flashed
Phototransistor voltage [V]: 0.188
that would target your PC or smartphone. inside her MCU. Upon starting the MCU,
Box temperature [degC]:      +10
Please watch [5] for a basic explana- the Trojan will act as a bootloader and
Battery voltage [V]:       2.775
tion of the problems related to solid-state change a few lines in the MCU’s program
Min temperature [degC]:      -5 memory devices at very high level of (e.g. fill them with NOPs using the AVR’s
Max temperature [degC]:      +30 integration. notorious SPM command) to disable for
Cause of zeroization: A hardware backdoor Trojan consists instance some crucial protective actions.
Capacitor Cx2. kCx2= 0.656 of extra circuitry added to the MCU’s The possibility of a successful attack

component list

60 May & June 2020 www.elektormagazine.com


of this kind is much lower than with a found to function well.
general-purpose Trojan. However, some carriers are
rougher than others and
Is there any defense? it turned out to be neces-
Luckily for Alice and Bob, there are many sary to block C1x and C2x
ways to counter this kind of hardware to avoid them to come
threats. The simplest is to return to loose. Sticking non-con-
1980’s technology and use a simple Z80 ductive foam or bits of
system like [6] with SRAM and EPROM as plastic on top of them is
separate ICs. The EPROM is erased with one method. If the MCU
UV light and needs a voltage of 13-14 V is mounted in a socket,
on its Vpp pin to be written, making you might want to block
it much harder to plant a hardware it too. The battery sits
backdoor. Furthermore, the internal quite tight in its holder,
architectures of the Z80 and 27C-type but you never know.
EPROMs (produced in many millions for If you have other
over 20 years) are very well known, suggestions for
and it is easy to decapsulate the IC and improving the device
inspect it under a microscope if needed. described in this article,
With millions of pieces lying around the especially regarding
globe, Mallory would have a very hard the hardware-backdoor
time rigging them all. defense part, please
Porting the MCU firmware of the TRNG or contact me through the project page at
OTP Crypto Shield to a Z80 can be done Elektor Labs [7]. I have a few ideas but Bob and Alice finally meet in person.
at the expense of execution speed and you may have better ones, and other
physical size, but the systems would still methods can always be proposed. To
work fine. Please note another miscon- confirm its security, any crypto device
ception of today’s design engineer- must be reviewed by a number of
ing here: small-, mini-, micro- and independent experts, so please feel free
nano-sized devices are not always better! to participate in any way!
Of course, a Z80-based system would As usual, the design files and source code
be too unwieldy and power-hungry to for this project can be downloaded from
be used for the paper-mail box, but this the project’s webpage [7].
problem can be solved in another way, 180445-01
with a little extra circuitry, everything
fitted inside the existing box.
If you studied the schematics carefully,
you may be wondering about the function
of K3. It is intended for an add-on circuit 4 sale @ www.elektor.com
to protect the box against hardware
ªTamper-Evident Box - panel of all bare PCBs
Trojans. More about this in a future www.elektor.com/180445-1
article in Elektor, so stay tuned!
ªTamper-Evident Box - preprogrammed microcontroller ATmega328P-PU
www.elektor.com/180445-41
Sounding off
ªIR Adapter - programmed microcontroller ATtiny45-20SU
The prototype of the box as shown on
www.elektor.com/180445-42
the photos has made several trips with
different land mail carriers and was

Web Links
[1] Random Number Generator: www.elektormagazine.com/labs/random-number-generator-150116
[2] One-Time Pad (OTP) Crypto System: www.elektormagazine.com/labs/one-time-pad-otp-crypto-system
[3] Erasing data from flash drives: www.schneier.com/blog/archives/2011/03/erasing_data_fr.html
[4] Data Remanence in Semiconductor Devices: www.usenix.org/legacy/events/sec01/full_papers/gutmann/gutmann.pdf
[5] Elektor video interview on security: www.elektormagazine.com/news/secure-communications-an-interview-with-luka-matic
[6] A small and simple Z80 computer: www.sunrise-ev.com/z80.htm
[7] Tamper-evident paper-mail box for secure distribution of one-time pads:
www.elektormagazine.com/labs/tamper-evident-paper-mail-box-for-secure-distribution-of-one-time-pads

www.elektormagazine.com May & June 2020 61


LABS PROJECT

Elektor New Precise


Nixie Clock Revisited
An engineering bulletin
for enthusiastic users new and old
By Andy Leitch (UK) and Luc Lemmens (Elektor Labs)

Elektor’s New Precise Nixie Clock a.k.a.


6-Digit Nixie Clock was among the top
ranking projects published in the past
five years, both in terms of readership
resonance and kit sales. Not resting on
our laurels, we compiled and now publish
a set of tweaks and enhancements for the
clock. The modifications are of different
levels and intents, and range from ‘nice to know /
optional’ right up to serious advice like extending your Nixie tubes’
lifetime. Although the mods have resulted in an updated clock board and a wholly new
backlight board, it’s very well possible to adapt your existing board and run the new software too.

Back in May 2016 Elektor Labs magazine minor adaptations. However, if you are
project decoder published the New Precise Nixie Clock satisfied with adding date display and
[1] and since then many readers either preventing/limiting tube cathode poison-
Nixie
purchased the complete kit or just the ing (more about that later), then replac-
PIC bare PCBs, and bought their own compo- ing or reprogramming the microcontroller
clock update nents to build the project. In fact, judging will suffice.
from the number of views as well as
entry level
tech-interested followers on the Elektor The most eye-catching enhancement
Æ intermediate level Labs website [2] it’s one of the most Andy made is the multi-colour backlight-
expert level popular designs of the past years. ing for the Nixie tubes to replace the
In the wake of the May 2016 publication, six blue LEDs from the semi-kit. Besides
1 hour approx. (upgrade/mods we received requests and suggestions to being decorative, the new backlighting
only);
enhance and extend the clock, especially also indicates what information is being
3 hours (semi-kit assembly) the software. That job was finally seen shown on the clock display. Andy used
to by one of the staunchest followers a strip of perfboard and through-hole
lab tools, on Labs, Andy Leitch. Andy completely WS2812 RGB LEDs for this, but in order
PIC programmer rewrote the software originally produced to make it completely tidy and easy to
in assembler, to ‘C’ and adapted the assemble, Labs designed a circuit board
hardware enabling the clock to also with the same LEDs in SMA housings.
€10 approx. (upgrade/mods only); display the date and act as an alarm This PCB is available from the Elektor
€140 approx. (semi-kit excl. case) clock, among other things. To fully exploit Store in the same black colour as the
the functionality of the new firmware now other PCBs from this project. More about
available [3], the circuit boards require it below.

62 May & June 2020 www.elektormagazine.com


+180V

R1 R2 R3 R4 R5 R24 R25 R26

27k
27k
27k
27k
27k
27k

470k
470k
hours-10 hours-1 mins-10 mins-1 secs-10 secs-1
V1 V2 V3 V4 V5 V6
1 Nixie IN12 1 Nixie IN12 1 Nixie IN12 1 Nixie IN12 1 Nixie IN12 1 Nixie IN12
LA1 LA2

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

2 11 10 9 8 7 6 5 4 3 12 2 11 10 9 8 7 6 5 4 3 12 2 11 10 9 8 7 6 5 4 3 12 2 11 10 9 8 7 6 5 4 3 12 2 11 10 9 8 7 6 5 4 3 12 2 11 10 9 8 7 6 5 4 3 12

1 2 1 2 1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4 3 4 3 4
5 6 5 6 5 6 5 6 5 6 5 6
7 8 7 8 7 8 7 8 7 8 7 8
+180V
9 10 9 10 9 10 9 10 9 10 9 10
K4 K6 K8 K10 K12 K14
V1.0 1 2 V1.1 V2.0 1 2 V2.1 V3.0 1 2 V3.1 V4.0 1 2 V4.1 V5.0 1 2 V5.1 V6.0 1 2 V6.1
V1.2 3 4 V2.2 3 4 V2.3 V3.2 3 4 V3.3 V4.2 3 4 V4.3 V5.2 3 4 V5.3 V6.2 3 4 V6.3
LA1 5 6 V1.3 V2.4 5 6 V2.5 V3.4 5 6 V3.5 V4.4 5 6 V4.5 V5.4 5 6 V5.5 V6.4 5 6 V6.5
T8
7 8 MPSA42 V2.6 7 8 V2.7 V3.6 7 8 V3.7 V4.6 7 8 V4.7 V5.6 7 8 V5.7 V6.6 7 8 V6.7
+180V
9 10 V2.8 9 10 V2.9 V3.8 9 10 V3.9 V4.8 9 10 V4.9 V5.8 9 10 V5.9 V6.8 9 10V6.9
K5 K7 K9 K11 K13
K3

+5V 1 2 11 10 13 14 8 9 16 15 +5V 1 2 11 10 13 14 8 9 16 15 +5V 1 2 11 10 13 14 8 9 16 15 +5V 1 2 11 10 13 14 8 9 16 15 +5V 1 2 11 10 13 14 8 9 16 15


R6 O8 O9 O6 O7 O4 O5 O2 O3 O0 O1 O8 O9 O6 O7 O4 O5 O2 O3 O0 O1 O8 O9 O6 O7 O4 O5 O2 O3 O0 O1 O8 O9 O6 O7 O4 O5 O2 O3 O0 O1 O8 O9 O6 O7 O4 O5 O2 O3 O0 O1
10k 5 IC1 12 5 IC2 12 5 IC3 12 5 IC8 12 5 IC9 12
C6 GND C4 GND C5 GND C16 GND C17 GND
T1 100n 74141 100n 74141 100n 74141 100n 74141 100n 74141
MPSA42 A0 A1 A2 A3 A0 A1 A2 A3 A0 A1 A2 A3 A0 A1 A2 A3 A0 A1 A2 A3

3 6 7 4 3 6 7 4 DIM1 3 6 7 4 3 6 7 4 DIM2 3 6 7 4
T3
R7 MPSA42
10k

T2
MPSA42
R23 33 34 35 36 15 16 17 2 3 4 5 27 28 29 19 20 21 22
14
13 OSC2
10k OSC1

RB1
RC1
RA1

RB0
RB2
RC0
RC2
RA0
RA2

RB3
RA3
RD0
RD1
RD2
RD3

RD4
RD5
RD6

39 31 +5V
RB6 VSS
R9 38 12
RB5 IC4 VSS
T4 37 R11
10k RB4
MPSA42 11
10k

VDD
PIC18F45K22
R8 32
10k VDD 1 rst +5V
+5V

RD7
RC5
PGD
RA5
RC3
RC4
RC7
RC6
RE2
RE1
RE0
RA4

+5V R27 K15


PICkit 0R27 D7 30 24 40 7 18 23 26 25 10 9 8 6 RA4
+180V
rst
RE0
D1
+ RE1
0 L1 RE2
PGD 6 1 +5V
D OKI-78SR-5/1.5-W36C 100µH BYY26 R13 +5V RC6
PGC SC
5
470k

D2 CI GND
IC6
C7 1N5814 7 +5V
1 3 IS T5 P1 R15
100n 8 IRF644 R28 R12
K1 DC D3 500k
10k

C10 D4
2

www.elektormagazine.com
SE
1k

BAT46
47k

GND
3 BAT46 MOD1
2 IC7 TC 10µ
T9 250V 1W VCC
C12 C13 C15 MC34063 C18 BC557 C11
10µ 100n 220µ GND

Figure 1: Circuit digram of the the revised New Precise Nixie Clock. This version incorporates all changes to the original design of 2016.
100µ GND 100µ
25V 25V C3 25V R16 C1 R17 S1 NC
4 25V
5k6

1k

+ TXD
470p 100n LED1 - PPS
Bz1

May & June 2020


63
New features,
new circuit diagram
The hardware and some of the software
modifications to the New Precise Nixie
Clock have resulted in a new schematic
printed in Figure 1. This schematic
matches the new printed circuit board now
included in semi-kits of the New Precise
Nixie Clock sold through the Elektor Store.
The instructions are for the old PCB; the
new version V2.1 version does not need
any hardware mods.
Figure 2: Cutting a PCB track to disconnect one neon from its driver. (change applies to existing
Button modification PCBs only)
Status: mandatory.
The existing toggle switch is best
replaced with a momentary-action
type. This very simple modification will
open most features of the new software.
Simply unsolder the existing switch and
replace with a pushbutton. You may need
to drill out the mounting hole to suit the
replacement switch, but if you use one
with a 4.95-mm shaft, it will fit without
drilling.

Preventing cathode poisoning


Status: highly recommended.
If a Nixie tube is operated without
regularly exciting all the numbers, the
Figure 3: Interconnecting the neon lamps with a wire. (change applies to existing PCBs only)
unused wires tend to get coated by a
highly resistive sputtered material.
The effect is commonly referred to as
cathode poisoning. It will result in dark essential. A low-current device is needed
spots or segments of the numbers when and these are easily obtained from
they should completely be lit. If Nixies Amazon, eBay, RS components, etc. A
are used in a clock, the seconds digit is search for 3–24 V piezo buzzers should
unlikely to be affected by cathode poison- find a suitable candidate. Check the
ing as it cycles through all numbers supply current is 10 mA or less, as the
every ten seconds, but other digits are PIC can only supply 25 mA out of the
in danger. port pin.
Cathode poisoning can largely be pre- The sounder is polarity-sensitive and is
vented (or at least limited) by tempo- connected black wire to pin 1 of JP1 (at
rarily cycling every tube through all its the edge of the PCB) and red wire to the
numbers every now and then, and that is pin on the PIC side. R14 can be desol-
exactly what the new software does. The dered or cut from the board. A small hole
first ‘cleaning’ will be done at power-up in the back of the case allows sound out,
and is repeated every 30 minutes (at and the sounder can be glued in place.
15 and 45 minutes past the hour). If
installed, the WS2812 backlight will Date display modification
blink and cycle through colours when Status: optional.
the ‘preventive cleaning’ is performed. This tweak is needed to show the date in
This option can be switched off in the EU format (dd/mm/yy) as a 3 is needed
clock’s settings. for displaying of the days on the leftmost
digits. The PCB is laid out to drive the
Alarm sounder modification two neons separately, and the ‘3’ digit
Status: highly recommended. of the left Nixie tube is not connected.
Figure 4: Connecting the ‘3’ element of Nixie Although in principle this is only needed It is modified to join both neon lamps to
tube V1 to the middle pin on top of K4. (update if alarm clock function is used, the beep one driver, and then connect the ‘3’ to
applies to existing PCBs only) when setting parameters is in practice the now unused driver.

64 May & June 2020 www.elektormagazine.com


LED1 LED2 LED3 LED4 LED5 LED6
WS2812B WS2812B WS2812B WS2812B WS2812B WS2812B

C1 C2 C3 C7 C4 C5 C6
100n 100n 100n 100µ 100n 100n 100n
VDD VDD VDD VDD VDD VDD
+ R1 16V
0 100 DI DO DI DO DI DO DI DO DI DO DI DO
D
VSS VSS VSS VSS VSS VSS
K1

180588-002-94 KD

Figure 5: Circuit diagram of the decorative backlight board implemented with SMD LEDs. Note the decoupling capacitors which are needed to suppress
noise caused by the relatively high current.

• Step 1: disconnect one neon from


its driver. The lower track on the
tube side of the PCB is cut with a
craft knife. It is cut again approx-
imately 1 mm along so a small
section of track can be peeled away,
see Figure 2.
• Step 2: Connect the neons together,
see Figure 3.
• Step 3: Connect the ‘3’. It connects
to the middle pin, top row, of K4,
see Figure 4.

WS2812 ’Neopixel’ LED


Backlight
Status: optional.
Figure 6: The vacated crystal connections on the PCB are connected to driver IC pins bent aside.
Caution: The LEDs need 5 V but quite
(update applies to existing PCBs only)
a lot of current. You can use a second
5 V regulator powered from the inlet
9 V supply, or get power, ground and better change it to a switching type (e.g. the project other than for programming,
data from the programming header. If Murata OKI-78SR-5/1.5-W36-C). so a little code was added to enable it to
you take power from the programming The schematic of the lively backlight is drive the backlight LEDs — the driving
header, you need a heatsink on IC6, or shown in Figure 5. Pin RB7 is not used in signal comes out on header K1, pin 4.

component list

(C) Elektor
180588-1 V1.1

K1
LED1 LED2 LED3 LED4 LED5 LED6
D0 +

R1 C7

C1 C2 C3 C4 C5 C6
+

www.elektormagazine.com May & June 2020 65


component list

66 May & June 2020 www.elektormagazine.com


The WS2812 SMD type LEDs are mounted the PCB and the module to avoid short Conclusion
on the Labs PCB with a surface mount circuiting the shielding of the module to Although the original New Precise
10 µF, 16 V capacitor in the middle of a via underneath [2]. Nixie Clock runs beyond reproach with
the board and 100 nF capacitors at the Both Maestro GPS modules have a default the equally original software, the new
supply pins of each LED. The first LED has serial output of 4800 baud. Many other version presented here offers several new
a 100-Ω resistor in series with the data modules are available, but usually run features that are worth the update. If
wire from the RB7. Alternatively, you at 9600 baud. you should do all the hardware changes,
can build your own backlight board using Fortunately, as part of the software well… that’s up to you, of course. If you
stripboard (perfboard/Veroboard), and rewrite, the clock now features auto pick just a few, fine! The authors believe
through-hole versions of the WS2812. baudrate detection on the GPS module. the upped GPS reception, the anti-cath-
Labs went for SMD components not only ode-poisoning feature and the multi-co-
because this type of LEDs is easier to Operating instructions lour backlight are absolute enhancements
align, but also because this flat design fits With the new software running there is a for this beautiful and nostalgic clock!
into the acrylic case without any mechan- single button to control the clock. Short 180588-01
ical issues. presses change the display or parame-
ter; long presses change the mode, in
Dimming accordance with the current display. All
Status: recommended. options, settings and parameters avail-
The 74141-compatible decoders show able to configure and adjust the revised
blank for input values upwards of 9. To New Precise Nixie Clock may be found in
flash, and therefore dim, all the digits, the user manual produced by Andy and
two chips need to have their ‘bit 3’ pin stored at [2].
(i.e. pin 4) connected to the processor
instead of ground.
If dimming is enabled in the settings of
the clock without the modification, then
the digits will show ‘7’ instead of turning
off. The quartz crystal has to be de-sol-
dered. Repeatedly heat one end at a time
in turn and gently lift X1 out, the two
capacitors C8 and C9 are also removed.
Two of the decoder chips, IC2 and IC8,
are lifted out. Pin 4 is straightened
carefully, and then the ICs are re-in-
serted. Watch out for legs getting bent
under when re-inserting! Use an old
turned-pin IC socket or a female jumper
cable to connect to the chip — do not
solder as soldering causes leakage which
is visible during dimming.
Link the pins to the now empty crystal 4 sale @ www.elektor.com
connections with single core wire, as
ªNew Precise Nixie Clock, (revised) PCB, bare, 150189-1 V2.1
shown in Figure 6. www.elektor.com/180589-1
ªNew Precise Nixie Clock, Backlight PCB, bare, 180588-1 V1.1
GPS module
www.elektor.com/180588-1
Status: recommended.
ªProgrammed PIC18F45K22 (DIP-40), 180588-41
Over the past months Labs received a
www.elektor.com/180588-41
few questions from readers wanting to
build the Nixie clock and buy the compo- ªGPS module
www.elektor.com/open-smart-gps
nents separately but having failed to find
a source for the A2035H GPS module
from Maestro Wireless Solutions. It
turned out this part is no longer in
production. Fortunately, Maestro now
Web Links
has the A2235H, a newer GPS module
that does fit on the old PCB (although the [1] New Precise Nixie Clock, Elektor Labs magazine May & June 2016:
module is smaller than its predecessor). www.elektormagazine.com/magazine/elektor-201605/28960/
However, it needs two additional 2.2-kΩ [2] Project/Engineering web page:
pullup resistors from the I2C pins to the www.elektormagazine.com/labs/150189-6-digit-nixie-clock
1.8 V output of the module. You may also [3] Project/Publication web page: www.elektormagazine.com/180588-01
need some (Kapton®) isolation between

www.elektormagazine.com May & June 2020 67


Practical
ESP32 Multitasking (3)
Software timers
By Warren Gay (Canada)

Microcontroller developers often need timers, to perform retransmissions and other error recovery
procedures, for debouncing of button presses, or just for a blinking LED indicator. The ESP32 device and the
Arduino IDE provide software timers using the included FreeRTOS library. In this third part of the series we
focus on the timer facility.

In order to illustrate how FreeRTOS timers work, we’ll work with simply adding the line:
a demo assignment to construct an alert LED class. This is not static AlertLED alert2(13,1000);
your average blinking LED however. When activated, it quickly  
blinks five times and then is off for the rest of the period, and Our demonstration will focus on one indicator but the C++
repeats. It will visually appear as an attention getting alert or class packaging makes for convenient use.
as a visual phone ring alert.
The AlertLED class will use one FreeRTOS software timer inter- The AlertLED class
nally for each LED driver. As a class, you will be able to add as The class definition is copied below for convenience. The class
many as you need, without burdening the memory utilization data members include the member thandle (line 11), which is
of the ESP32. Listing 1 illustrates the full program [2]. Line a handle to the FreeRTOS timer (type TimerHandle_t). Initially
100 shows the creation of an alert LED instance with a simple it is assigned the value of nullptr (same as the C language
C++ declaration statement: NULL). The data member named state will track the LED state
static AlertLED alert1(GPIO_LED,1000); (line 12), which is active high (true = on). The data member
  count (line 13) will be used in the callback as a substate, which
The class instance name here is alert1, using the specified is explained later. Finally members period_ms and gpio config-
LED (GPIO 12 from line 5), and the flash period of 1000 milli- ure the blink period in milliseconds and the GPIO to drive for
seconds. We could easily add another one for GPIO 13, by the LED (lines 14 and 15).

68 May & June 2020 www.elektormagazine.com


Listing 1: The alertled.ino program [2]. 0064: }
0065:
0001: // alertled.ino
0002: // MIT License (see file LICENSE) 0066: //
0003: 0067: // Method to stop an alert:
0004: // LED is active high 0068: //
0005: #define GPIO_LED      12 0069: void AlertLED::cancel() {
0006: 0070:   if ( thandle ) {
0007: // 0071:     xTimerStop(thandle,portMAX_DELAY);
0008: // AlertLED class to drive LED 0072:     digitalWrite(gpio,LOW);
0009: // 0073:   }
0010: class AlertLED { 0074: }
0011:   TimerHandle_t     thandle = nullptr; 0075:
0012:   volatile bool     state; 0076: // static method, acting as the
0013:   volatile unsigned count; 0077: // timer callback:
0014:   unsigned          period_ms; 0078: //
0015:   int               gpio; 0079: void AlertLED::callback(TimerHandle_t th) {
0016: 0080:   AlertLED *obj = (AlertLED*)
0017:   void reset(bool s); pvTimerGetTimerID(th);
0018: 0081:
0019: public: 0082:   assert(obj->thandle == th);
0020:   AlertLED(int gpio,unsigned period_ms=1000); 0083:   obj->state ^= true;
0021:   void alert(); 0084:  
0022:   void cancel(); digitalWrite(obj->gpio,obj->state?HIGH:LOW);
0023: 0085:
0024:   static void callback(TimerHandle_t th); 0086:   if ( ++obj->count >= 5 * 2 ) {
0025: }; 0087:     obj->reset(true);
0026: 0088:     xTimerChangePeriod(th,pdMS_TO_TICKS
0027: // (obj->period_
0028: // Constructor: ms/20),portMAX_DELAY);
0029: //  gpio        GPIO pin to drive LED on 0089:   } else if ( obj->count == 5 * 2 - 1 ) {
0030: //  period_ms   Overall period in ms 0090:     xTimerChangePeriod(th,
0031: // 0091:       pdMS_TO_TICKS(obj->period_ms/20+
0032: AlertLED::AlertLED(int gpio,unsigned period_ obj->period_
ms) { ms/2),
0033:   this->gpio = gpio; 0092:       portMAX_DELAY);
0034:   this->period_ms = period_ms;
0093:     assert(!obj->state);
0035:   pinMode(this->gpio,OUTPUT); 
0094:   }
0036:   digitalWrite(this->gpio,LOW);
0095: }
0037: }
0096:
0038:
0097: //
0039: //
0098: // Global objects
0040: // Internal method to reset values
0099: //
0041: //
0100: static AlertLED alert1(GPIO_LED,1000);
0042: void AlertLED::reset(bool s) {
0101: static unsigned loop_count = 0;
0043:   state = s;
0102:
0044:   count = 0;
0103: //
0045:   digitalWrite(this->gpio,s?HIGH:LOW);
0104: // Initialization:
0046: } 
0047: 0105: //
0048: // 0106: void setup() {
0049: // Method to start the alert: 0107:   // delay(2000); // Allow USB to connect
0050: // 0108:   alert1.alert();
0051: void AlertLED::alert() { 0109: }
0052: 0110:
0053:   if ( !thandle ) { 0111: void loop() {
0054:     thandle = xTimerCreate( 0112:   if ( loop_count >= 70 ) {
0055:       "alert_tmr", 0113:     alert1.alert();
0056:       pdMS_TO_TICKS(period_ms/20), 0114:     loop_count = 0;
0057:       pdTRUE, 0115:   }
0058:       this, 0116:
0059:       AlertLED::callback); 0117:   delay(100);
0060:     assert(thandle); 0118:
0061:   } 0119:   if ( ++loop_count >= 50 )
0062:   reset(true); 0120:     alert1.cancel();
0063:   xTimerStart(thandle,portMAX_DELAY); 0121: }

www.elektormagazine.com May & June 2020 69


0010: class AlertLED { 0019: public:
0011:   TimerHandle_t     thandle = nullptr; 0020:   AlertLED(int gpio,unsigned period_ms=1000);
0012:   volatile bool     state; 0021:   void alert();
0013:   volatile unsigned count; 0022:   void cancel();
0014:   unsigned          period_ms; 0023:
0015:   int               gpio; 0024:   static void callback(TimerHandle_t th);
0016: 0025: };
 
0017:   void reset(bool s);
0018:
The class also includes some public method calls including:

• alert() - activate the LED indicator (line 21)


• cancel() - disable the LED indicator (line 22)
 
ESP32 There is also a C++ static method named callback() in line
GPIO12
24. More will be said about this later.

Method AlertLED::alert()
220

The method alert() and callback() are the most interesting


parts of the class. We noted that the handle was initialized as
nullptr. When the alert() method is called for the first time,
it will find the value to be null in line 53, causing the timer to
Figure 1. The wiring of the demonstration program alertled.ino.​ be created.
The software timer is created by the use of xTimerCreate() in
lines 54 to 59, returning the handle of the newly created timer.
The assert() macro in line 60 tests for successful creation.
The arguments to xTimerCreate() are:

1. A user friendly string name of our timer (here it is simply


“alert_tmr”). This is not used by FreeRTOS other than
for some statistic gathering functions. It normally should
be unique but does not have to be if you don’t perform
lookups by name.
2. A timer period in system ticks (converted from milliseconds
in line 56 using the pdMS_TO_TICKS() macro).
3. This indicates whether the timer is “one shot” (value
Figure 2. The LED drive signal for alertled.ino, horizontal is 200 ms / div. pdFALSE) or an “auto-reload” timer (value pdTRUE). Our
example creates an auto-reload timer (line 57).
4. This is a “Timer ID” in FreeRTOS terminology. This should be
thought of as a “user data parameter”. It is a void pointer,
which in this example, is the address of the class object
using the C++ reserved keyword this (line 58).
5. The address of the callback function. In line 59, we supply
the name of the static method AlertLED::callback(). This
is the function that will be called when the timer is triggered.
Some data members are reset by calling internal method
reset() in line 62, and followed by starting the timer in line
63 using xTimerStart(). All timers are created “dormant”
until they are started/restarted. Once started, they enter the
“running” state.

Static method AlertLED::callback()


The AlertLED class defines a static method call named
callback(). For those unfamiliar with C++, this means that
the method is just a function. As such, it has no implied object
pointer (no “this” pointer). It is the same as a C function except
for the funky C++ name and the fact that it enjoys special
access to the internals of the class object.
The software timer callback requires one argument of type
Figure 3. ESP32, LED and 220 ohm resistor wired for the alertled.ino TimerHandle_t (line 79). This gives us access to the timer
demonstration. handle that is being triggered but we need more informa-

70 May & June 2020 www.elektormagazine.com


tion - in that case the LED instance which should be driven. To prove that the AlertLED class can activate and cancel, the
Line 80 obtains this information using the “Timer ID” value loop() function maintains a count variable named loop_count
- the address of the (LED) class instance (alert1) using the (line 101). Function setup() initially activates the LED, but
pvTimerGetTimerID() call, which needs the timer’s handle. when the loop count reaches 50, the alert is canceled in line
This retrieves the value we supplied in line 58, when the timer 120. When the loop count later reaches 70, the alert is reacti-
was created. We can now get access to the LED object and its vated in line 113, and the counter reset.
members by the variable obj. When the program is flashed to the ESP32 and running, you
Lines 83 and 84 toggles the configured GPIO for the LED. Then should see the alert LED flashing in an attention getting manner.
the value of count is incremented (line 86), and until the count A little while later it will turn off, only to resume again. Figure 2
reaches 9, we simply return from the callback. This performs the illustrates the LED drive signal.
simple on/off fast blinkling for the first half of the alert period. Figure ​3 shows the setup, using a resistor LED combination
When the count reaches 9, lines 90 to 93 are executed. The and a Dupont wire to GND.
function xTimerChangePeriod() alters the time period used by
the timer we created. Notice that period_ms/20 is added to FreeRTOS limitations
the period_ms/2, to compensate for the last dark half of the So far, we have applied the software timer API, without saying
fast blink time. too much about some important limitations of the callback.
Finally, on the 10th time into the callback, lines 87 to 88 are These limitations include:
executed. The data members are reset by calling internal • Never perform a blocking call within the callback (like
method reset() (line 87), and the timer period re-estab- delay() or a blocking queue push for example).
lished for a fast blink in line 88. Because the data member • Avoid long execution times (this will disrupt the API).
count is cleared to zero, the whole cycle repeats. The auto-re- • Avoid using too much stack space (ESP32 Arduino is
load nature of the timer will keep the pattern repeating until probably limited to about 1500 bytes). Functions like
AlertLED::cancel() is called. printf() and snprintf() often require considerable stack
space and thus should probably be avoided in the callback.
Method AlertLED::cancel() • Some of the FreeRTOS API functions operate through
To stop the alert from blinking, AlertLED::cancel() method is an internal queue. This is why our demo program used
used. To accomplish this, xTimerStop() is called (line 71), and portMAX_DELAY in lines 88 and 92. The timer queue depth
the LED is forced off by writing LOW to the LED’s GPIO in line 72. for the ESP32 Arduino is 10, which is unlikely to get full,
unless many timers are involved at once.
The need for volatile
The alert reader will have noticed that we used the volatile C Summary
keyword in lines 12 and 13 of the class definition. Why is this You might wonder why not simply use a task to manage each
necessary? This informs the compiler that whenever it reaches alert LED? The main reason for this is that each task requires a
for the data member values state or count, that it should go stack and a task control block (TCB). If you needed to allocate
directly to the memory of the class instance (alert1 in our for 32 LED indicators, this would require 32 x (356 + 1500)
demo) rather than depend upon a value that might still exist bytes, totalling 59,392 bytes! Contrast that to the FreeRTOS
in a register. There are two tasks interacting with your class: timer approach requiring 40 bytes for each timer, for a total
of 1200 bytes (object type StaticTimer_t is 40 bytes). The
• The FreeRTOS daemon class (via the callback) stack is shared with the FreeRTOS daemon task for all timers
• Your task that invokes the alert() or cancel() methods of (previously known as the timer service task).
the class. Applications might mix and match approaches for special needs
but many times a FreeRTOS timer satisfies the requirements.
If these values were not marked as volatile, either or both tasks 200071-01
might use values that are still in a register, since this is normally
the optimal thing to do. However, the values in memory may
have changed by the other task. For this reason the keyword
volatile causes the compiler to disregard this possible optimi-
zation and generates code that fetches the values directly from
memory instead.

The demonstration
For a simple demo alertled.ino, we can again use the Lolin
ESP32 OLED Display Module. The wiring is shown in Figure 1.
The LED is wired according to the active-high configuration.

Web Links
[1] Practical ESP32 Multitasking, Elektor Magazine 1/2020: www.elektormagazine.com/190182-01
[2] Project source code: https://github.com/ve3wwg/esp32_freertos/blob/master/alertled/alertled.ino

www.elektormagazine.com May & June 2020 71


HOMELAB PROJECT

SigFox and the


IoT (4)
Setting up a dashboard

By Frank Schleking and Bernd vom Berg (Gernmany)

Our short series of articles closes with a look at the development of a custom dashboard to help visualize
measurements sent over the Sigfox network, both graphically and numerically.

In the previous instalments of this series we examined the received by the Sigfox backend, and stored. And from that
basic Sigfox hardware for acquiring and transmitting measured point we can proceed to visualize the data on a dashboard.
data and the concepts underlying data transmission in the
Sigfox network. Our measurements are now sitting in the Sigfox The thinger.io dashboard platform
backend waiting to be picked up and processed further. We will be using thinger.io, an open source IoT visualization
A free web-based dashboard tool is available that lets the platform which enables the rapid and straightforward construc-
user create and operate a custom visualization and monitor- tion of clear and attractive data visualizations. It can even be
ing interface on any PC, laptop, tablet or smartphone. And, if used free of charge for simpler projects.
suitably enabled, this dashboard can be called up and viewed The system at the moment does not support mathematical
by anyone (or just by any authorized user) over the Internet operations on the received data, and that means that the
from anywhere in the world. readings must be delivered to it in a form already processed and
The starting point for the developments described here is the ready to display. However, the required processing can easily
Arduino sketch Sigfox-3_0.ino running on the MKR FOX 1200 be handled by our Arduino software running on the MKR FOX
board. If you select the fourth menu item ‘Send three readings’ 1200 board. The model for visualizing the data values is based
then the three measured quantities (atmospheric pressure, on a dashboard or instrument panel which can be made publicly
air temperature, and light intensity as recorded by the LDR) available to anyone with a web browser.
will be continuously acquired, the results being shown on the
ePaper display on the motherboard and output over the serial Step by step
monitor to the Arduino IDE. When the button is pressed these A few simple steps are required to develop a custom dashboard
readings will be automatically sent over the Sigfox network, as follows.

72 May & June 2020 www.elektormagazine.com


Figure 1. Home page of thinger.io.

Figure 3. Main account screen showing statistics. Figure 2. Setting up a new account.

• Create a free user account at thinger.io. address you can go to the login page and log in. The main
• Set up a ‘data bucket’ at thinger.io to accept the readings screen of your account is called ‘Statistics’ and this is the start
sent from the Sigfox backend. point for all further actions (see Figure 3). The main menu is
• Set up an access point and token at thinger.io, and with it on the left-hand side, containing all the functions needed to
configure the Sigfox backend so that the Sigfox backend create a visualization dashboard for your IoT project.
has the necessary credentials to
transfer data to thinger.io.
• Set up a callback on the Sigfox
backend to send data over the
Internet from the backend to the
data bucket at thinger.io.
• Design a suitable graphical
dashboard on the thinger.io site
to visualize the data.
 
Creating a user account
at thinger.io Figure 4. Setting up a new data bucket.
A (free of charge) user account has
to be set up at thinger.io in order to
use its services. To do that, go to the
thinger.io homepage [1] (Figure 1)
and click on ‘Sign up’ at the top right.
This will take you to the form for
registering a new user (Figure 2).
Fill in the fields of the form and click
on ‘Sign up’.
The services available to users
with free accounts are somewhat
restricted, but nevertheless are more
than enough for most small experi-
mental projects. Full details on what
is available can be found under the
‘Pricing’ tab.
Once you have confirmed your e-mail Figure 5. Specifying the properties of the data bucket.

www.elektormagazine.com May & June 2020 73


Setting up a data bucket
at thinger.io
In the next step we set up a ‘data
bucket’, which is a database where
readings can be stored and from
which they can later be read back.
The Sigfox backend will automatically
write readings to this database using
Figure 6. Setting up a new token (access point). the Sigfox callback.
From the main screen click on ‘Data
Buckets’ on the left-hand side and
then on ‘Add Bucket’ (Figure 4). A
window will appear to let you config-
ure the characteristics of the data
bucket (Figure 5). The ‘Bucket id’
is a identifier that must be unique
within the whole account, and that
will later be used when configuring
the bucket to work with Sigfox. For
this example we enter ‘elektor’. The
fields ‘Bucket name’ and ‘Bucket
description’ can contain any text that
might be of help to the user. Use the
pull-down menu in the ‘Data source’
selection field to set its configuration
to ‘From Write Call’. That means that
Figure 7. Specifying the properties of the token. the data will be sent to thinger.io over
the Internet from the Sigfox backend
using the Sigfox callback. As soon as
the callback sends the data values,
they will be stored here in the bucket. Finally, click on ‘Add
bucket’ and the bucket will be created.

Setting up an access point at thinger.io to receive data


from the Sigfox backend
The Sigfox backend must of course know where the readings
that it has acquired should be sent using its callback: in other
words, we have to tell the Sigfox backend the address of the
receiver at thinger.io. This step is done by creating a token
with the appropriate credentials to allow access to the data
bucket. In the main window click on ‘Access Tokens’ and then
on ‘Add Token’ (see Figure 6). A window will appear in which
you can enter the properties of the token (see Figure 7). First
we set the ‘Token ID’, which can be any value we like: for this
example we choose ‘elektor’.
Figure 8. Configuring token permissions. Under ‘Token Name’ you can add a free-text description of the
token or just a name.
Then click on ‘Add’ (the small green
button at the bottom right) and then a
‘token permission’ (i.e., credentials to
access the data bucket) will be added.
In the next step you will be able to
configure this in detail (see Figure 8).
In the ‘Select Permission Type’ field
select ‘Bucket’. In the ‘Access’ field
click on ‘Specific Bucket’ and then
choose ‘elektor’ (the identifier of
the bucket that we set up) from the
drop-down menu. Under ‘Actions’
choose ‘Select specific action’
Figure 9. The token is created and activated with the appropriate permissions. and in the field below that choose

74 May & June 2020 www.elektormagazine.com


‘WriteBucket’ from the drop-down
menu. Finally click on the ‘Add’
button: this will generate a token for
the target bucket that you selected
(with identifier ‘elektor’) and add it
to the ‘Token Permissions’ list (as
shown in Figure 7). Now click on ‘Add
Token’ (Figure 7, bottom left) and this
access point, which will be the recep-
tion address for messages from the
Sigfox backend, will be created in
thinger.io (Figure 9).
The important thing to note is the blue Figure 10. Choosing the desired device type.
‘Access Token’ field, which contains
the authentication credentials gener-
ated by thinger.io that the Sigfox
backend will require.
The Sigfox backend will need to be
configured so that it sends this access
token code to the thinger.io destina-
tion address along with the payload
data: this will ensure that the payload
it sends will be accepted by thinger.io
and correctly directed to the ‘elektor’ Figure 11. The callback window.
data bucket. It is therefore necessary
to copy-and-paste this access code
and store it safely somewhere.
With that we complete the configu-
ration of the parameters at thinger.
io and we can return to the Sigfox
backend.

Configuring the callback


in the Sigfox backend
We want to arrange things so that
when the MKR FOX 1200 sends data
to the Sigfox backend, the infor-
mation is automatically forwarded
to thinger.io for further processing
and visualization. To do this we use
a feature of the Sigfox backend that
we have mentioned a few times before
known as a ‘callback’. A callback is
nothing more than an automatic data
forwarder that is executed whenever
the Sigfox backend receives data from Figure 12. There is a wide selection of possible types of callback.
a Sigfox station such as our MKR FOX
1200. The backend must of course
be correctly configured to enable this
forwarding, ensuring that the data are sent to the desired entry in this case) click on the device type name ‘Arduino_
recipient. DevKit_1’: see Figure 10. The overview page for this device
In order to transfer the data payload to our thinger.io ‘elektor’ will then appear. In the list on the left click on ‘Callbacks’ (see
data bucket we need to make use of our token and the access Figure 11). If you now click on the small button marked ‘New’
token code that thinger.io has generated for us in the previous at the top right of this window a list will appear giving all the
step. In other words, the backend will make an HTTP connec- different types of callback available that work with the most
tion over the Internet to access the token, and then uses the widely used dashboard and cloud programs (Figure 12). From
access token code to authenticate itself. Once successfully these select ‘Custom callback’. In the window that now appears
authenticated it can write data into the data bucket. you will be able to configure the callback and how data are
In order to set up the callback first log in to the Sigfox sent from the Sigfox backend to thinger.io (see Figure 13).
backend [2]. On the main page click on the ‘Device Type’ tab Note that at this point it is essential to take care that all the
and in the list that then appears (the list will only have one entries you make on this page appear exactly as described

www.elektormagazine.com May & June 2020 75


below: the tiniest mistake will result in
error messages and indeed the whole
system not functioning correctly.
A detailed description of how the
individual settings work is beyond the
scope of this article: very compre-
hensive information can, however,
be found at [3], [4] and [5]. Let us
begin at the top of Figure 13. Under
‘Type’ the correct settings are ‘DATA’
and ‘UPLINK’, and for ‘Channel’ select
‘URL’, as it is over an HTTP connection
that we will be talking to thinger.io.
Now things get a bit more tricky. The
data values sent from the MKR FOX
1200 in the payload to the Sigfox
Figure 13. Configuring the callback. backend need to be unpacked back
into individual values within the Sigfox
backend. Internally to the backend
each value is assigned a freely-cho-
sen variable name. These names are
used in specifying the further process-
ing that the backend does on the
variables’ values. The way the Sigfox
payload is unpacked is specified in
the ‘Custom payload’ field, and of
Figure 14. Starting to create a dashboard.
course must mirror the way the data
values are packed into the payload
on the MKR FOX 1200. We need to
specify precisely the sequence of data
in the Sigfox payload, the data types
involved, and the storage format, in
order for the payload to be unpacked
correctly into the individual variables.
For our example the ‘Custom payload
config’ should contain three elements,
each appearing precisely as follows.
 
temp::float:32:little-endian
pressure::float:32:little-endian
ldr::uint:16:little-endian
Figure 15. Basic parameters of the dashboard.  
The first data value packed into the
payload sent by the MKR FOX 1200
is therefore the temperature reading.
In the Sigfox backend this is given
the name ‘temp’ and has data type
‘float’, represented using four bytes
(32 bits).
The second data value in the payload
is the atmospheric pressure, also a
Figure 16. List of available dashboards. ‘float’ variable represented using
32 bits.
The third and final value in the
payload is the LDR voltage. In the
backend this is given the name ‘ldr’,
and is a variable of type ‘uint’ stored
in two bytes (16 bits).
The term ‘little-endian’ specifies the
order of the bytes used to store a
Figure 17. The dashboard in edit mode. given value: little-endian is the order

76 May & June 2020 www.elektormagazine.com


used by our Atmel microcontroller. Further information on this
can be found at [6]. You should enter the above three elements,
concatenated into a single line and separated by spaces, into
the custom payload configuration field. You can now configure
the Sigfox backend to process these three variables, or, alter-
natively, you can send them directly to thinger.io in this form.
Under ‘URL pattern’ you specify the destination URL at thinger.
io. The URL is constructed in the following way.

https://api.thinger.io/v1/users/{user_id}/buckets/
{bucket_id}/data

In the address replace user_id with the user name from your
thinger.io account (from Figure 2) and bucket_id with the
bucket identifier, here ‘elektor’ (from Figure 5), in both cases
without curly brackets or quotation marks.
Under ‘Use http Method’ select ‘POST’. Figure 18. First window for creating a widget.
The next step is to set up authentication for the data transfer
to thinger.io. This is done in the two fields next to ‘Headers’.
In the ‘header’ field enter the word ‘Authorization’ and next to
that, in the ‘value’ field, enter ‘Bearer’, followed by a space and sends a variable with name AtmPressure. The value of this
then the access token that we created as shown in Figure 9. variable corresponds to the value of the backend variable called
pressure, which we previously specified in the ‘Custom payload
Bearer eyJhbGci7j76j67jzI1NiIsIn ... etc. config’ field. The keyword customData# indicates that the value
of a variable unpacked using the ‘Custom payload config’ field
In the field ‘Content type’ enter ‘application/json’, which is to be inserted. This is how the variable names and values
indicates that the body of the message is in JSON format. are reformatted for transmission to thinger.io.
In the final step we specify exactly what will be sent to thinger. The last two lines are processed in the analogous way.
io. The entry (in JSON format) in the ‘Body’ field should be as Each line, apart from the last, must be terminated with a
follows. Again, it is essential that the text appears precisely comma.
as shown.  
That completes the configuration of the callback in the Sigfox
{ backend to enable it to send the desired data to the ‘elektor’
    "Device-ID" : "{device}", data bucket at thinger.io. When you have completed all the
    "AtmPressure" : {customData#pressure}, above steps correctly, you can click on ‘OK’.
Now, when the MKR FOX 1200 sends a payload to the Sigfox
    "Temperature" : {customData#temp},
backend, and assuming that no errors are encountered in recep-
    "Light-Sensor" : {customData#ldr}
tion, the Sigfox backend callback will immediately forward
}
the data in the format specified above to thinger.io for further
  processing.
The ‘Body’ is enclosed in curly brackets (‘{‘, ‘}’). But what
does the text in the body mean? The dashboard at thinger.io
Each line between the curly brackets begins with a double Now we come to the last piece of the puzzle, adding some
quotation mark; after that appears an freely-chosen (but polish to our project. We want to present the data in graphical
unique) variable name, followed by another double quotation form on a dashboard. In order to create a dashboard, go to
mark. There follows a space, a colon and another space. It the main thinger.io console (Figure 3) and on the left click on
is at this point that the value of the variable will be inserted ‘Dashboards’ and in the next screen on the ‘Add Dashboard’
by the Sigfox backend. The variable name and its value will button (see Figure 14).
subsequently be sent in this format to thinger.io, where it will You now need to fill in the fields in the ‘Dashboard details’
be stored in the appropriate data bucket. window (Figure 15). The ‘Dashboard id’ is an identifier unique
So we have across the entire account. The fields ‘Dashboard name’ and
‘Dashboard description’ can be filled in with any information:
    "Device-ID" : "{device}", they are intended to be easily user-readable. Confirm the entries
by clicking on ‘Add Dashboard’. The new dashboard will be
which will give the unique device number of the Sigfox station added to the ‘Dashboard list’ which you will see whenever
(i.e., our MKR FOX 1200), which is known to the backend. This you click on the ‘Dashboards’ menu item in the main console
information is sent along with the measured data so that the window (as shown in Figure 16).
originating station can later be identified uniquely. If you click on the name of the dashboard, a design window
The line will appear displaying an empty dashboard (see Figure 17). At
the top right there is a small switch: slide this to green to enter
    "AtmPressure" : {customData#pressure}, edit mode. There are also two buttons labelled ‘Add Widget’

www.elektormagazine.com May & June 2020 77


and ‘Settings’. In thinger.io the dashboard display elements
that form part of the user interface are termed ‘widgets’. A
wide range of widgets is available, including time-series charts,
doughnut charts, progress bars, analogue displays, Google
maps with position information, images, text displays, LEDs
and a clock. In our application we would like to show a time-se-
ries chart for each of the three measured values and a digital
display for each showing the most recently received value.
Click on ‘Add Widget’ and a window entitled ‘Widget Settings’
will pop up (see Figure 18). Under ‘Type’ you can choose the
type of widget you would like to add. In this case we choose
‘Time Series Chart’. Two further tabs will appear, as shown in
Figure 19. In the ‘Time Series Chart’ tab, under ‘Chart Input’,
select the ‘From Bucket’ option. As you proceed more and more
fields will appear that need to be filled in. In the ‘Select Bucket’
Figure 19. Configuring a time-series chart.
field choose the bucket ‘elektor’. In the next field, ‘Select Fields
to Plot’, choose the data value that is to be displayed.
We begin with ‘AtmPressure’. Under ‘Timeframe’ choose
‘Relative’ and set the time window to be displayed to ‘12 hours’.
This will cause the graph to display the most recent 12 hours’
worth of data; of course this can be adjusted if desired. Click
now on the ‘Display Options’ tab (Figure 20) and turn off the
‘Multiple Axes’ option: we are going to set up a separate graph
for each of our variables, and so we do not require multiple
Y-axes on the same graph. The ‘Axis’ option (already enabled)
causes the X- and Y-axes of the graph to be scaled automati-
cally. In the field next to the ‘AtmPressure’ label we can choose
the colour in which the graph will be plotted: here we have gone
Figure 20. Setting the basic characteristics of the display.
for a soothing shade of green. If you enable the ‘Fill Splines’
option the region between the plot and the X-axis will be filled
with the colour selected next to the ‘AtmPressure’ label. The
‘Legend’ option allows the plots to be labelled separately. Of
course this is really only useful when more than one time series
is plotted on the same chart.
 
Finally we return to the ‘Widget’ tab (see Figure 21), where
we can now set the title and subtitle for the chart. We will set
the ‘Title’ field to ‘Atmospheric pressure’ and the ‘Subtitle’ field
to the unit of measurement, ‘hPa’. If desired the ‘Background’
setting lets you adjust the background colour of the whole chart;
however, we do not want to over-egg this particular pudding
and will stick with the standard white. We finish setting up
the chart by clicking on ‘Save’: the chart will be added to the
dashboard (see Figure 22). You can make the chart larger or
Figure 21. Settings in the ‘Widget’ tab.
smaller by clicking in the bottom right-hand corner, and the
mouse can also be used to drag the chart around the dashboard
area. Resizing the chart is not perfectly smooth, and so it will
tend to jump around a little.
We also want to display the current atmospheric pressure
reading in digital form (Figure 23). The ‘Add Widget’ button
again opens the menu for adding a new element to the display;
in this case in the ‘Type’ field we select ‘Text/Value’.
In the ‘Widget Value’ field we again select ‘From Bucket’, choose
the ‘elektor’ bucket and again specify which value we want
to display (here ‘AtmPressure’). For the ‘Bucket Value’ we set
‘Latest Value’. The ‘Display Options’ tab allows us to make
various configuration settings. For example, we can set the
precision to which the value is displayed (‘Decimal Places’) and
we can set the ‘Units’ field to ‘hPa’. This string will be displayed
Figure 22. The time-series chart added to the dashboard: a few readings in the widget next to the measured value. There are further
are already plotted. configuration options that can be set if required, but we will

78 May & June 2020 www.elektormagazine.com


Figure 23. Configuring the digital display for the atmospheric pressure reading.

Figure 24. The completed dashboard. Figure 25. General dashboard settings.

not explore them further here. In the ‘Widget’ tab we again is shown in Figure 24. Note that in order to ensure that all
set the ‘Title’ field to ‘Atmospheric pressure’. We can leave the entries and modifications are stored in thinger.io, it is neces-
‘Subtitle’ field empty, as we have already arrange for the unit sary to exit editing mode and then re-enter it. More informa-
to be displayed next to the value. tion on designing dashboards on thinger.io can be found at [7].
That completes the configuration of the dashboard display Now we just need to enable access to the dashboard ‘from
elements for atmospheric pressure. The display for the other outside’. Back in the Dashboard menu click on the blue button
two readings are configured in a similar way: the final result labelled ‘Settings’, which will take you to the dashboard settings

Figure 26. Output from Sigfox-Demo.ino on the serial monitor and on the ePaper display.

www.elektormagazine.com May & June 2020 79


Figure 27. The dashboard looks good on a smartphone screen!

page (see Figure 25). Here you can give your dashboard a Sigfox network, which corresponds to about one message every
name and a description (although in this case it is not necessary ten minutes. In view of that it is less critical that a free account
as we have already set this up). The switch labelled ‘Share’ at thinger.io only entitles you to write data to a bucket at most
enables the dashboard for external access: the (rather lengthy) once a minute. Figure 27 shows how natty the dashboard we
link required to access it will appear in the field labelled ‘Share have created looks on the screen of a smartphone.
URL’. Using this link it is now possible to access the dashboard
from anywhere in the world and examine the data it displays. In conclusion
Because of the length of the URL it is recommended to use a With that we come to the end of our short series of articles
URL shortener such as bitly.com to abbreviate it. The short- introducing the world of the Sigfox 0G network. The highly
ened URL can then be converted into a QR barcode that can flexible and versatile programming of the Arduino MKR FOX
be scanned by a smartphone: this avoids the bother of having 1200 enables the acquisition of a broad spectrum of types of
to tap in the long URL. data and their transmission over the Sigfox network all over
It is worth noting that when you enable public access to the the world. Meanwhile the simple yet powerful visualization
dashboard at thinger.io it is automatically write protected: possibilities offered by thinger.io allow the rapid and efficient
that is, it can only be read. Third parties cannot alter settings development of custom dashboards for communicating infor-
or make other adjustments: this is only possible after using mation to end users.
the appropriate credentials to log in to the thinger.io portal. We wish you every success on your forays into the exciting
We would now like to test the system as a whole. However, it is world of the Internet of Things!
somewhat annoying to use the Sigfox-3_0.ino Arduino sketch 190281-D-02
to do this, as it is necessary to press a button each time we
want to send a message. To help out there is another sketch,
called Sigfox-Demo.ino, included in the software download [8].
At ten-minute intervals this program automatically acquires
the three readings and transmits them (see Figure 26). The
4 sale @ www.elektor.com
interval between transmissions is determined by the value of ªArduino MKR FOX 1200
the global variable w_zeit and can be adjusted if desired, so www.elektor.com/19096
you can arrange to acquire and display readings over a long ªArduino Antenna 868 MHz
period of time. However, always keep in mind that you are only www.elektor.com/19095
allowed to send a maximum of 140 messages per day on the

Web Links
[1] Thinger: http://www.thinger.io/
[2] Sigfox backend: https://backend.sigfox.com/
[3] Information on configuring Sigfox callbacks: https://support.sigfox.com/docs/callbacks-documentation
[4] Information on creating custom Sigfox callbacks: https://support.sigfox.com/docs/custom-callback-creation
[5] Information on the Sigfox callback API: https://backend.sigfox.com/apidocs/callback
[6] Byte ordering when storing numeric values: https://en.wikipedia.org/wiki/Endianness
[7] Information on designing a dashboard: https://github.com/thinger-io/Docs/blob/gh-pages/console/dashboards.md
[8] Project web page: www.elektormagazine.com/190281-D-02

80 May & June 2020 www.elektormagazine.com


start-up zone
 Start-Up Update:
The Elektor Investment Program
By the Elektor Start-Up Team

Elektor nurtures and empowers electronics-focused start-ups (e.g., hardware,


software, and technical services) through events, competitions, and business
solutions. The Elektor Investment Program [1] is a new service for both young
companies and investors looking to connect and excel in the electronics industry.

What is the Elektor Investment Program? We also aim to assist investors. We know that
As a start-up or scale-up, there comes a time when bootstrap- investors get dozens of pitch decks each year. And it takes a
ping is no longer an option. If you are lucky, you already have lot of time to read them all, and most of them are not good
some paying customers, but you will need money to take your enough. We realized that we could help investors save time by
business to the next level. Maybe you need to hire a team, connecting them with promising tech start-ups in our global
enter new markets, or extend your development. The most network that match their investment scope.
likely step is to talk with investors. As a founder, you might
ask yourself: Am I ready to pitch to them? Is my business Start-Up benefits
plan and pitch deck ready? Will investors take me seriously? Are you a member of a start-up or even scale-up in need of
Members of the Elektor Investment Program team will guide funding? By participating in the Elektor Investment Program,
you through this venture. We can help with your business plan, you can take smart actions to improve your chance of getting
assist you in preparing your pitch deck, and match you with funded. Sounds like a good deal, right? Here’s what we offer:
investors from our network. • Personal help to improve your pitch deck and business plan.
• Business analysis to make a profile of your company.
• The opportunity to be connected to matching investors
(based on your profile) from our network.

Investor benefits
The Elektor Investment Program can help investors find innova-
tive companies. In addition to running successful start-up
competitions, our professional start-up team scouts for promis-
ing companies around the world. Companies that join the
program are screened by our experts, so we assist investors
with promising leads. We provide:
• Access to high-potential technical start-ups and scale-ups
that match your investment scope.
• Proper documentation, professional business connections,
and a business analysis of your matches.

Join the Elektor Investment Program!


Want to join the Elektor Investment Program or learn more
about it? Visit the program site [1] or email Arthur Lampe
Why did Elektor start the program? (Elektor’s Investment Program Manager) today on arthur.
If you simply send your pitch deck to investors and hope for [email protected] to get started. Good luck!
the best, you could get declined for any number of reasons. 200112-01
Perhaps you contact the wrong investor. Or maybe your pitch
deck lacks important information. One thing is for sure: you
need to make the most of your pitch opportunities. Web Links
So, why did we set up the Elektor Investment Program? We’ve [1] Elektor Investment Program:
been running start-up competitions for a few years [2], and www.elektormagazine.com/widgets/investment-program
we’ve been interacting with many promising start-ups all along
[2] Elektor Start-up Competitions:
the way. Developing a program to further help start-ups find
www.elektormagazine.com/select/fast-forward-award
funding and partners was a logical next step.

www.elektormagazine.com May & June 2020 81


review
Joy-IT HD35
Electronic USB Load
Test & verify USB power performance
By Dr Thomas Scherer

Since its introduction over 25 years ago the USB port has become the de-facto standard for communications
between a PC and its peripheral equipment. In the meantime, in an effort to reduce the plethora of non-
standard wall-wart mains adapters, most other devices with built-in rechargeable batteries like mobile
phones, tablets etc. use the 5 V supply pins of this port for charging. It’s even possible to fit a mains outlet
wall plate with a built-in 5 V supply and USB socket. With the introduction of Quick Charge the power supply
communicates with the device being charged to negotiate an output voltage. A compliant charger can output
a higher voltage and current beyond the typical 5 V / 2 A rating of the standard USB charger.  With so many
essential devices relying on a fully-functioning charger and so many different fast-charge standards emerging
it is convenient to have a single unit that can quickly check that the charger is doing everything it should...

When I saw this little device called the JT-HD35 from


Joy-IT on the Internet, I was curious. An electronic load for
the USB port? Another crazy idea dreamt up in the Far East! designed into a product
But as I read in more detail what this test unit can do, it all for production but can also be used
became a bit clearer. It can be used to test the performance to ensure that an off-the-shelf charger
of all types of USB ports. This is not only useful to test a port really can provide the power quoted in its spec sheet. I have

82 May & June 2020 www.elektormagazine.com


Figure 1. This small plastic box contains the JT-HD35 USB load tester. Figure 2. The plastic box from below showing technical data and the
manufacturer’s URL.

Figure 3. The USB load module in all its glory. It’s all there: three USB Figure 4. Underside of the USB load module (Image. Joy-IT).
inputs, fan, display, three LEDs, three pushbuttons (the third is under the
board) and a potentiometer.

already reviewed another USB test device from Joy-IT[1] called Unboxing
the UM25C — but this one here is a different kettle of fish with The load tester consists of a single board and is supplied in a
different capabilities. translucent plastic box (Figure 1) with the picture on the lid
showing what is inside. Apart from the USB load tester board
Features there is no documentation or links to any sites where the
The Joy-IT JT-HD35 is a compact, electronic USB load resistor documentation can be downloaded. The underside of the box
able to measure and display the output power up to 35 W from is printed with the main features of the load tester but again no
a USB port or charger. It can test the output of a standard 5 V links (Figure 2). This is no great loss because it’s no problem
USB charger as well as those compliant with some of the more to Google the company name and find the user manual for this
recent fast-charge standards. device in PDF format [2].
The key features of this unit are: I prefer to store this type of document in an ‘Instructions’
folder on my PC; it saves tedious searches by hand — and a
• Operating voltage: 4 to 25 V (DC) PDF is ideal as it can be searched for keywords in most cases.
• Load current: 0.25 to 5 A First of all, I was keen to see how far I could use the device
• Power: max. 35 W without resorting to the manual.
• Indicators: 3 status LEDs (green, blue, red) Figure 3 shows what’s in the small plastic box. The unit consists
• Display: 4-digit 7-segment display LED, red of an assembled PCB with a heatsink and fan fixed in place
• Operation: 3 buttons, 1 multiturn potentiometer (load using only two screws. On the underside shown in Figure 4 you
current adjust) can see the TIP122 power Darlington and an LM317 regulator
• Connections: USB 2.0, Micro-USB, USB-C which are mounted on the underside of the heatsink. The NPN
• Fan: 40 mm, 0 to 8000 rpm, temperature controlled Darlington transistor is rated at 65 W max. and is probably
• Dimensions: 84 x 41 x 28 mm used as the variable load to dissipate the power. Also on this
• Weight: 52 g side is a microcontroller labelled U1 = N76E003AT20, which is

www.elektormagazine.com May & June 2020 83


a small extremely low-cost (€0.28) 8051 derivative. Spaced
out across the board are a sprinkling of peripheral chips and
passive components. Because the writing on these tiny SMD
components is not easy to read, I usually take photos of them
and enlarge the result (see Figure 5).

Testing, testing…
I selected two power supplies/chargers with three cables as
guinea pigs (Figure 6) for the USB load tester. The little black
one on the right with the micro-USB to USB-A cable is a cheap
standard charger with 5.1 V and 1 A load capacity, as it used to
come with many (old) smartphones. It cannot deliver anything
much more than five watts. The white ‘smart’ power charger
from RAVPower is surrounded by a USB-A extension cable and
a USB-C cable. It supplies 5 V at 2.4 A from its USB-A socket
and not only 5 V at 3 A from the USB-C socket, but also 9 or
15 V at 2 A or 20 V at 1.5 A thanks to its compliance to QC
Figure 5. This close-up clearly shows the chip’s identification marks. 3.0. The total power output amounts to 36 watts, which ties in
nicely with the rated power handling of the JT-HD35.
After switching on, when connecting to the black charger, the
voltage is shown in two digits on the display, i.e. about ‘5.1 V’.
After a little erratic operation of all the pushbuttons, I think I
got some idea how this thing works: pressing the ‘SET’ button
cycles the display to show voltage, power (initially ‘0.0P’) and
current (here flashing ‘1.00A’). Now if you press the OK button
once, the current setting value stops flashing and remains
constant. Then after about 20 s the cooling fan kicks in. This
indicates that when the displayed current is flashing it shows the
required value of load current but without the load connected.
When the displayed current is continuous it indicates that the
load is connected. Another press of the ‘OK’ button removes
the load and sets the display value flashing again.
By adjusting the multiturn pot setting while testing the small
black charger under load I increased the load current to 1.1 A
and noticed that the output voltage dropped to 3.5 V. It was
reassuring to find that the charger has some built-in over-cur-
rent protection. It was also interesting to see that micro-USB
connector is unsuitable to deliver high levels of current. Even
Figure 6. These two power supplies are about to be put through their with a current limited to 1 A the voltage drop across the connec-
paces. tor resulted in a measured supply at the load of 4.9 V, whereas
the USB-A extension cable used with the same power supply
delivered 5.0 V.

Now with the USB-A socket of the RAVPower unit connected


to the load tester via a USB-A lead its current limit starts to
activate at around 3 A. Connected via the USB-C cable, it was
possible to crank up the load current to 3.88 A before the power
supply shut down (see Figure 7). It looks like the technical
spec for the RAVPower charger is quite modest when it comes
to its maximum output current rating.

And now?
After testing it with 5 V USB supplies I wanted to move on and
try various other voltages according to QC 2.0 or 3.0. At first
I wasn’t sure how I could change the mode but after search-
ing through the manual it became obvious I had overlooked a
pushbutton on the underside of the board. This is the ‘trigger’
button — used to activate the curiously named ‘trigger/decoy’
feature. I guess the JT-HD35 could be thought of as a kind of
Figure 7. Proof: The RAVPower QC 3.0 compliant charger can supply decoy device which sends appropriate acknowledgements to
3.88 A via USB-C at 5 V. the charger, to make it switch its output (surely ‘Mode’ would

84 May & June 2020 www.elektormagazine.com


Figure 8. Connections, displays and controls of the JT-HD35 (image modified from Joy-IT original).

be a better label). I added clearer labels to identify the button Conclusion


in the photo shown in Figure 8. All in all, this inexpensive electronic USB load is functional and
A long (2 seconds) press of this pushbutton switches the unit does exactly what it’s supposed to do. The decision not to include
out of its default (5 V) to the other modes. The display should a printed copy of the operator’s manual is a big thumbs-up to
first show ‘-5.0’ to indicate it is in QC 2.0 mode. The red LED help reduce unnecessary waste. The standard of documenta-
flashes and you can use you the ‘+’ and ‘-‘  buttons to adjust tion is quite poor and just about covers the basics of operation.
the charger voltage output in steps through 5/9/12/15/20 V. This is only to be expected for such a low-cost piece of test kit
Further presses of the trigger push button get into the other that only gets occasional use. When it comes to displaying the
modes including ‘AUTO’ which can identify if the charger has word ‘Auto’ or ‘OTP’ I think even I would be able to work out a
a quick charge function — in this mode message exchange better representation of the letter ‘t’ on a 7-segment display.
can take up to 25 s to complete. Although USB was originally There is always room for improvement… I would like to see
conceived as a universal interface to reduce e-waste, various better signage for the trigger pushbutton and a better red filter
companies such as Huawei, Samsung and Apple now offer fast over the 7-segment display to improve readability. All in all,
charge schemes which are not interoperable. A recent vote in this USB load does what it says on the tin. It is inexpensive
the European parliament however returned a massive major- and, thanks to the fan, can dissipate high power levels for
ity in favour of making iPhones and Androids use the same extended periods. The maximum power handling is 35 watts
charger — this could mark the end for Apple’s Lightning Cable and it did not get over-warm when I ran it at 30 watts so it
in Europe when the law comes into force in the summer. should be able to take whatever the current USB charging
According to its specification the JT-HD35 can provide load tests specification can throw at it. If you think you can make use of
for chargers designed for standard QC2.0, QC3.0, Huawei’s FCP this electronic load to test a USB power supply this is a good,
fast charge system, Samsung’s AFC9 and ‘other quick charge convenient low-cost solution. You could hardly build one more
modes’ although it is not specific what these other standards cheaply yourself from scratch.
are. Without any of these quick chargers to hand I was unable 200049-02
to test this feature of the device.

Without reference to the manual, I certainly struggled to change


the operating mode. Operation of this electronic USB load was 4 sale @ www.elektor.com
(for me) not entirely intuitive. For my needs I am only seldom
ªJoy-It JT-HD35 USB Load Tester
likely to make use of a test device like this. Chances are when
www.elektor.com/joy-it-jt-hd35-usb-load-resistor-35-w
I come to use it again in three months time I will have forgot-
ten how it works.

Web Links
[1] Review: The Joy-It UM25C USB Tester:
www.elektormagazine.com/news/review-the-um25c-usb-tester-with-color-lcd-and-bluetooth
[2] JT-HD35 operating manual: https://www.joy-it.net/files/files/Produkte/JT-HD35/JT-HD35-Manual.pdf

www.elektormagazine.com May & June 2020 85


HOMELAB PROJECT

CAN Bus + Arduino


for Solar PV Cell Monitoring
Detect and locate serviceable panels in large arrays

image: Shutterstock

By Somnath Bera (India)

Why limit the use of the exquisite CAN bus to in-vehicle sensorics? That’s what the author thought when
customers, installers and authorities bickered about disappointing results from a 25 kW solar cell array on
commercial exploitation. Here’s how an electronics system got designed to read out the power yield of each
PV panel individually along with its number so the serviceman can pinpoint it and clear the source of the
problem (literally — read on).

The situation: a roof-mounted solar PV cell array comprising place which is thick with birds like crows and pigeons. The
55 panels, each generating 24 volts and up to 25 kilowatts droppings are so frequent that almost all PV panels get the
in total supplied to a large single-phase, 220-V out, inverter, complete share in about a fortnight’s time.
charging a large battery array well out of sight. The consumer: The remedy I suggested was to wash each panel with water
a conglomerate of shops requiring electricity for evening sales every alternate day, and as a long-term measure, to move
and other activities. The shops were supposed to get six hours the panels away to a place with fewer birds in the air above.
of lighting from 5:30 pm to 11:30 pm. The setup was inaugu- The regular cleaning restored the performance to the origi-
rated with a great fanfare in the presence of a big shot who nal level and after a while it turned out that only selective
came down from headquarters. cleaning was sufficient to maintain the performance, rather
than the alternate-day scheme. Still the washer person had
Wash & wipe to visually check all the panels first and then proceed to the
The solar PV array, inverter, and the battery system worked selective cleaning. The checking takes substantial time as the
fine for some time but slowly, over a couple of months, the worker has to go round all the panels to see which ones need
performance deteriorated such that even with charging periods cleaning. For the 55 panels involved this was rather easy but
of 10 to 12 hours, the ’evening’ power did not last for more for TAD’s next setup, a 100-kW PV panel array, a nightmare
than 3 to 4 hours. The brick batting started. The local Township loomed for the cleaning person or staff. In short, TAD wanted
Administration Department (TAD) started blaming the installers to know instantly which panel in the array needs cleaning so
for poor quality installation, cheap PV products etc. But a quick that the “bucket & mop” person can go straight to that panel
glance at the rooftop mounted PV panels revealed the mystery and do the surface cleaning in no time.
in no time. The 55 panels worth 500 watts each are spread
over three rooftops, and huge numbers of pigeons and crows Enter the CAN bus
were flying right above them. Most of the PV panels were dirty Control Area Network (CAN) using the cheap Arduino is a great
and covered in at least two major servings of bird dropping. solution for measuring the performance of the individual PV
The shopping complex is situated adjacent to the local market- panels. The CAN bus was invented by Bosch within the automo-

86 May & June 2020 www.elektormagazine.com


Arduino Uno

Solar PV
MCP2515 CAN
SCK
S0
H
SI

120
CS
GND
L

8
D13 VCC
IOREF
RES

ARDUINO
3V3
- +
5V
GND
+
D9
X
GND
VIN D7 X
ACS712
A0 Relay Board X
X
D0
X
Buck Charger X
+
(5V)
5V
GND X
- X
CAN1 X
X
X
X
X
Arduino Uno X
X
Solar PV
X
MCP2515 CAN X
SCK
S0
H
X
SI
CS X
GND
L X
8
D13 VCC
IOREF
RES
X
ARDUINO

3V3
- +
5V
GND
+ X
GND
VIN
D8
D7 X
ACS712
A0 Relay Board X
X
X
D0
X
+ Buck Charger 5V GND
X
(5V) X
Shielded twisted-pair cable
-
CAN254 X
X
X
X
Arduino Uno X
X
Solar PV
X
X
MCP2515 CAN X
SCK
S0
H X
SI
CS X
GND
L X
8
D13 VCC
IOREF
RES X
ARDUINO

3V3
- +
5V
GND
+
X
GND
VIN
D8
X
ACS712
D7
Relay Board X
A0
X
X
D0 X
Buck Charger
+ 5V GND
(5V)
-
CAN255
120

Figure 1: Block diagram showing the modules, devices and cables involved in making a CAN bus based monitoring system for a solar panel array with
up to 120 (!) PV panels (just 3 shown here). Each panel is individually monitored for failing output current due to whatever cause. One Arduino UNO is
assigned the CAN Bus Master level, the others are slaves.

www.elektormagazine.com May & June 2020 87


tive industry and permits the collecting of signals from hundreds
of sensors fitted and connected in a vehicle. Parameters sensed simple current sensor is connected at the load terminal of each
for a modern car include ambient temperature, tyre pressure, PV panel. The ACS712 is a Hall-effect “probe” for measuring
brake fluid level, engine temperature, speed, AC temperature current. The -30 version can measure current up to 30 amps.
and many more. All sensors are connected on just two wires in The barrier strip is for connecting the device in series with the
a bus structure and connected to the central computer which PV power circuit. Assuming Chinese sourcing, the ACS712-30
monitors the sensors’ output signals and if necessary responds costs around $2.00 apiece. For DC readings from an ACS712-
by issuing control commands to relevant sensors, again over 30 current sensor with its ‘out’ pin connected to the Arduino
the two-wire bus. UNO A0 pin, you simply program
The CAN bus runs from node to node using a shielded twist- load_current = 0.075714*(analogRead(A0) – 512)
ed-pair cable having an impedance of 120 ohms. For proper
matching and to reduce signal reflection, both end nodes on The UNO’s 5 volt supply comes from a small Buck charger
the CAN bus have a 120 Ω termination resistor. connected to the 24 volt PV cell bus. The buck charger should
For a cheap CAN bus transceiver we use the MCP2515 chip, cost around $2.00 apiece. Its main advantage is adding
which normally comes from China at under $1.50. At the micro- extremely little power dissipation to the monitoring system.
controller side it’s SPI ready and at the CAN bus side it has a Besides accumulation of dirt, grime and pollen, other factors
barrier strip for connecting the CAN H (high) and CAN L (low) that degrade PV cell performance include humidity resistance
bus wires. The bus is implemented with good quality, durable, (small bubble formation on the surface), snail trails (discoloura-
shielded twisted-pair copper cable. For the microprocessor we tion of the surface), micro cracks and hot spots. Any and all
propose the ATMEGA328 sitting on an Arduino UNO, which of these may cause the PV cell output to go down by as much
receives the sensor signals on its digital and analogue I/O pins. as 35% which is measurable in terms of the output current.
In order to control actuators you can connect relays, servos Since we are not overly interested in measuring the absolute
and other output devices on the remaining I/O pins. current contribution of the panel, we can make do with the
For simplicity we will use only CAN 2.0 which can carry 0 to 8 value returned by
byte data at a time from one node to another. All the nodes load_current = analogRead(A0) – 512
including the master get an identifier (0 to 255) through which
the communications get sent & received. The lower the identi- This ‘value’ gets compared with a set reference as well as with
fier the higher up in the order of devices sending & receiving. values from other panels with a view to deciding to raise an
Usually the bus master gets the lowest identifier. The CAN bus alarm or not. Having seen the alarm and the location (number),
(protocol) has excellent error checking capability. the cleaning person will go to the offending panel and check
The number of nodes can vary from 0 to 130 on a single CAN for dust, dirt and pollen before washing it once. If that fails
bus and the length also varies from a few meters to few kilome- to solve the problem, the next level is a check for hot spots,
tres. Reduced data speed means larger distances between the excessive humidity resistance etc. In the worst case the panel
end nodes. However, for anything beyond a few hundred meters needs to be replaced.
a CAN bus repeater should be used to ensure noise immunity
and signal integrity The maximum number of nodes permissible Can Bus 4*4
on a typical CAN 2.0 bus around 120, which is still way more The project allows for a 4*4 keyboard to be incorporated on
than the 32 offered by an alternative like the RS485 MODBUS. the CAN bus, for control purposes and local entry of numbers.
Figure 2 shows the schematic and Figure 3, the experimental
BUS Bus Cable Stub setup on the author’s workbench. You will see the keyboard
speed Length Length being used as an option in the project software.
1000 kbit/sec 40 m 0.3 m
500 kbit/sec  110 m 0.3 m The project software
250 Kbit/sec 240 m 0.3 m The software deveped for the project takes the form of a bunch
125 Kbit/sec 500 m 0.3 m of Arduino sketches and is hosted on the Elektor Labs website
[1] along with some updates and notes from the author. The
100 Kbit/sec 500 m 0.3 m
software should be taken as a starting point, not as a finished,
50 Kbit/sec 1300 m 0.3 m
slick application, and is intended to spur your ingenuity and
20 Kbit/sec 3300 m 0.3 m creativity once “the numbers are in reach”. It is broadly classi-
10 Kbit/sec 6600 m 0.3 m fied in two parts: master or slave. A slave picks up the DC
5 Kbit/sec 13 km 0.3 m reading from the A0 port and relays it to the master. The master
has two modes of operation: Master in display mode, or Master
in control mode. The CAN master is given the ID ‘1’ while the
A solar PV panel health monitor other units are assigned ‘254’ and ‘255’ like in Figure 1, or
Using the CAN bus we can add up to 120 solar PV panels and any other number between 2 and 253. The maximum number
read their individual performances, i.e. the voltage and the of nodes is 120.
current contributed by each one to the total of DC fed to the  
inverter. A suggested block schematic for a PV cell performance Master in display mode: This is achieved by using digital
surveillance system is given in Figure 1. I/O pin D10. When D10 is high the master goes into display
Being connected in parallel, all PV cells in the array produce mode, collecting data from all the slaves and displaying them
the same voltage but different output currents. Therefore, a in a grid structure. It then finds out if any signal (i.e. power

88 May & June 2020 www.elektormagazine.com


Arduino Uno

SCK MCP2515 CAN


S0 H
SI

120
CS
GND
VCC L
Solar PV

8
D13
D12
X

ARDUINO
D11
5V
GND
+
D9 X
D7
7 4 1 X
A0
A1
* X
X
- + 0 8 5 2
X
D0
# 9 6 3 X
X
D C B A X
Buck Charger 5V X
+
(5V) 4x4 Keypad X
- X
X
190035-006-94 KD

Figure 2: Schematic of the CAN Bus Master with a 4x4 keypad for use in control mode.

level) is under the desired level and goes on to issue an alarm


for the cleaning of that particular panel. This mode is optimum
for PV array monitoring.
 
Master in control mode: When D10 is open or low, the master
goes into control mode. In that case the nodes are connected
to relays driven through digital pins D0 to 8. There is a 4*4
CAN keypad connected on the master CAN device (ID = 1).
The master issues a command string like
 
25581#,25580#,13011#
 
etc. and the respective node relays are switched on or off to
control, say, a shower and/or a wiper connected to the PV
cells. Examples:

25580# : 255 is the node number; 8 is the digital pin number;


0 is off; 1 is on.
Figure 3: Experimental version of the CAN Bus master controller extended
25471# : 254th node, relay connected to the digital pin 7 and
with a 4x4 keypad.
a 1 to energize it.
25130# : 251st node, Digital-3 relay, off.
 
The hash character (#) is used to terminate the command. A system like the one described here also enables many small
The CAN bus master can have its own PV current sensor, units connected on the CAN bus to be controlled from a central
connected to its A0 pin or it may be devoid of any PV panel desk. Other uses include hotel room alarm buttons for guests,
connected to it. and hotel lights. Instead of running all kinds of wiring inside
the building, a single twisted-pair CAN bus may be enough for
Your application? extensive, reliable control and measurement.
One alternative use of this type of configuration is to find out in 190035-01
a small city or park how many light poles are actually on or off.

Web Link
Project on Elektor Labs: www.elektormagazine.com/labs/can-bus-for-solar-pv-cell-monitoring

www.elektormagazine.com May & June 2020 89


all–analogue

Analogue Electronics Design (3)


Case Study #1 — Section 3:
Preamplifier response optimization
and trade-offs
By Ton Giesberts (Elektor Labs)

In this article series, experts in the field explore


aspects of analogue electronics design that should
benefit an increasingly ‘digital-only’ audience, and
underpin that analogue is not black magic. In this third and closing
instalment of the first Case Study in the series we revert to the microphone
preamplifier used in the Bat DetectorPLUS project [1], concentrating on those
features that set it apart from a routine audio preamp implemented with
opamps.

If you are new to this series, reference should be made to the result in feedback from the loudspeaker to the microphone. This
previous installments [1],[2]. For all readers to benefit from, is a mechanical problem, because even the best loudspeaker
the circuit of the microphone preamplifier we’re about to discuss is not ideal and will distort the sound. In the case of the bat
was extracted from the Bat DetectorPLUS full schematic and is detector, there are of course no requirements for really small
shown separately in Figure 1. Flashlights on and let’s do some signals as with an audio amplifier. A signal-to-noise ratio of
more design analysis on it. 20 dB in the signal going to the comparator is likely to suffice.

Dynamic range Bias currents


Because of the very high fixed gain and the low supply voltage of Seeing a 10 kΩ resistor fitted to each non-inverting input may
the preamplifier, there is a chance that the output will saturate raise the odd eyebrow. This is normally done to compensate
and clip, and when signals are too small, and/or frequency an extra offset caused by the bias currents of the opamp. But
dependent, the gain may be insufficient. The dynamic range is even at the maximum temperature range of a TL06x, those
determined by the maximum undistorted output signal and the currents through the JFET inputs are smaller than 5 nA. That
smallest usable signal well above the noise. Unlike ADCs and 5 nA across a 100 kΩ resistor drops a minuscule 0.5 mV, i.e.
DACs, S/N is not the same as dynamic range. The S/N of micro- almost negligible, also because there is no DC coupling between
phones is usually specified at 94 dB sound pressure (1 pascal), the various amplifier stages. Unless bipolar opamps are applied,
but for most microphones there is also a linear relationship the bias currents can amount to a few 100 nA or even µA. Only
between sound pressure and output voltage, usually up to then, this needs to be considered, depending on the resistance
120 dB. Then there is still minimal distortion and therefore the values of course. Also, the 10 kΩ resistors render the amplifier
dynamic range is considerably greater than the specified S/N. stages more sensitive to disturbances and unwanted parasitic
For the bat detector, it is obvious that adding a fast, automatic feedback. Consider replacing them with wire bridges.
gain control adapted (perhaps even limited) to the source
signal would be a good addition to further increase that range. Opamp as comparator
This could be something quite simple, like the classic circuit with The circuit also uses half a TL062 as a comparator. This is often
a JFET as variable resistor. This will also improve the detection of tempting to do when there is still an opamp left, or to use a
the modulation. There is hardly any danger of feedback (howl) dual version instead of a single opamp. Using a real comparator
if the high frequencies are filtered out properly at the power implies an extra IC. Comparators generally have an open-collec-
amplifier, preventing the loudspeaker from reproducing them, tor output and are not always advisable. The first thing to pay
if that should be a problem at all. Unfortunately, despite the attention to is whether the maximum differential input voltage
frequency separation, both harmonics in the output signal of the range is enough, and fortunately that is the case here. The
power amplifier and the reproduction by the loudspeaker can same goes for opamps sporting CMOS and JFET inputs. With

90 May & June 2020 www.elektormagazine.com


bipolar opamps like audio opamps,
+4V5
that range is often limited by an C13
4p7
C15
4p7
C17
4p7
extra network to protect the input R3

4k7
R6 R9 R12
transistors, e.g. a pair of diodes K1 100k 100k 100k
C12
in anti-parallel or Zener diodes in 1n R4
2
C14 R7
6
C16 R10
2 C18
7k5 7k5 7k5
anti-series. Also, if the specifications D3 R5 IC2A
1
1n R8 IC2B
7
1n R11 IC3A
1
3V C11 3 5 3
are exceeded, the output voltage 0W5
10k 10k 10k
470p
MIC. 100n
can flip over. A problem with the
TL062 is its maximum input offset, IC2, IC3, IC4 = TL062CP
-4V5
which is up to 15 mV, even up to 200100-002-94 KD

20 mV at the full temperature


range. An applied signal will have
Figure 1: The 3-stage microphone preamplifier designed into in the Elektor Bat DetectorPLUS has some
to compensate that offset before
remarkable features.
the output will toggle. In the case
of the detector, the sensitivity is
dependent on the exact IC used.
It’s a dependency we don’t want. +5V +5V

Another problem is the differen-


10k

tial voltage gain which is 3000 (D) Audio (D) V CC


FET FET
minimal according to the datasheet 1µ 1µ

and 6000 times typically, which


is actually too little to work

10k
(S) (S) Audio

properly as a comparator. To work (GND)


GND
(GND) GND

accurately, at least 10, possi-


bly even 30 times more gain is
needed. Take a real comparator
Figure 2: Schematic diagram for connecting a 2-pin electret microphone (left) and a 3-pin version (right).
like a LM311 or LM339, then that
In a 2-pin electret, the FET source and ground are already connected internally.
gain is typically 200,000.
The effect of the supply voltage on
the differential gain is not speci-
fied, but it would be interesting to know if it affects the rather output signal will deviate from the diaphragm voltage, causing
low ±4.5 V from the 9 V battery. To make proper rectangular a slight distortion.
waves at frequencies as high as 120 kHz, more bandwidth and With small signals, this effect is not that noticeable, but as the
certainly a higher slew rate is needed. With a comparator like sound pressure increases, the distortion rises and even becomes
the LM311 the slew rate depends on the differential signal, and visible on an oscilloscope. Also, the phase of the output signal
factually on overdriving. The larger this input signal, the faster can be inverted, but that is usually not a problem and can be
the output voltage changes, but even at 2 mV, around 30 V/ solved by reversing the polarization of the diaphragm.
µs is available mainly on account of the output transistor, and With 3-pin electret microphones, the source of the FET is also
not the pull-down or pull-up resistor. By contrast, the 3.5 V/µs available on the third connection, see Figure 2. We are not
slew rate offered by the TL062 in our design is somewhat low. talking about types with a built-in amplifier that need a real
supply voltage rather than biasing only. Using that third connec-
2- or 3-pin electret? tion, the FET can be configured as a source follower, reducing
For many, the electret microphone capsule will be familiar. Most the distortion. Unfortunately, the output signal is lower in that
types have just two connections. One is the ground connec- configuration. The drain connection is connected directly to the
tion (GND) and attached to the metal housing (screen). The positive power supply and the source is pulled down to ground.
other is the output signal taken from the drain (d) of an inter- The value of the pull-up resistor in the 2-pin, and the pull-down
nal JFET. The source (s) of the JFET is connected to ground. resistor in the 3-pin configuration, depends of course on the
A polarized diaphragm converts the sound into a voltage for type of electret microphone and the supply voltage. Always
the JFET’s gate (g). check the datasheet. MEMS microphones always have an IC
By inserting a pull-up resistor between the input of the micro- built in, so a real supply voltage is needed. There are tricks
phone amplifier and the supply voltage (which is usually quite to establish a 2-wire connection to a MEMS microphone by
low between 1.5 and 5 V), the FET is biased, and some ampli- placing a load at the output to vary the supply current, but
fication of the order of 10 dB already occurs inside the electret what happens to the specified properties is anyone’s guess.
microphone. The disadvantage is the non-linear steepness of a
FET. The steepness or transconductance gm is the relationship Calculation of the input noise
between variation of the drain current caused by variation of For the noise we have to calculate using a bandwidth of 120 kHz,
the gate voltage. Because this relationship is nonlinear, the rather than 20 kHz, the default range for audio. Worse, it is

www.elektormagazine.com May & June 2020 91


often only mentioned A-weighted. The well-known formula that (42 nV × √120000) × (1 + 100 / 7.5) = 0.21 mV
represents the noise as a function of temperature, resistance  
and bandwidth says: The total noise level at the output of the first amplifier stage
  in the Bat Detector works out at:
Unoise = √(4 k T B R) (Eq. 1)  
  √(0.4252 + 0.0472 + 0.212) = 0.476 mV
with  
k = Boltzmann constant (1.38 × 10-23 J K-1) giving a signal-to-noise ratio (S/N) of
T = absolute temperature (in K, 270 K is assumed)  
B = applicable bandwidth (in Hz) (100/7.5) × 8 mV / 0.476 mV = 224.1
R = resistance (in Ω)  
  or a solid 47 dB when expressed in decibels.
The total noise at the input is comprised of the noise already In other words, the noise at the microphone amplifier output is
present in the source signal (Unoise1) and the noise generated almost exclusively determined by the MEMS microphone. The
by the resistors (Unoise2) and the opamp used (Unoise3). contribution of the following stages is negligible with enough
  amplification. If the gain per section drops, the next amplifier
Unoise(total) = √((Unoise1)2 + (Unoise2)2 + (Unoise3)2) (Eq. 2) stages will also have an impact. This is another reason why
  eight sections with little gain is ill advised. And again, this
According to the datasheet, the noise of the microphone we calculation is only valid assuming the noise is linearly distrib-
used was measured with an A-weighted filter. That filter sadly uted and not approximately like the frequency characteristic.
is not specified for frequencies above 20 kHz, just the ultrasonic
area we need. It is even recommended to use a steep 20 kHz MEMS microphone straight on the PCB
filter in the sound pressure meters in combination with the Whether it makes sense or not we’ll leave aside for a moment,
A-weighted filter. This makes the statement in the datasheet but what would the practical application of a MEMS microphone
unusable. The only thing that is certain is that it will be consid- look like if it were mounted directly on the PCB? The following
erably larger for our calculation. So we make an assumption. proposals and queries can be taken as a starting point.
If we compare the A-weighted filter with a first-order 10 kHz
low-pass filter, then the noise at a bandwidth of 120 kHz is up by 1. Mounting a MEMS microphone on the PCB should be done
at least √(120 / 10) = 3.5 times, so roughly estimated (or even in such a way that the acoustic port has a good duct to
guesstimated) 11 dB higher for our calculation than stated in the the ambient air.
datasheet. Hence, a signal-to-noise ratio of 59 dB(A) at a sound 2. Is a rubber seal or anything else necessary? Is it possible
pressure level of 94 dB (1 pascal, Pa) and a bandwidth of 120 kHz to make a sealed connection to the housing of the detec-
is then estimated to be 48 dB if the measurement is unfiltered. tor so that moisture and dust etc. cannot penetrate the
At that sound pressure, an output level of –42 dBV is given MEMS microphone?
for 1 kHz, i.e. 8 mV. At 1845 times gain it yields 14.76 V and 3. Is it also possible to over reduce the frequency response
means an excessively overdriven amplifier. But ultrasonic, above and sensitivity? The use of a bottom-port MEMS microphone
40 kHz, the output level of our MEMS microphone decreases will be better for the shortest possible acoustic path to the
and between 10 and 20 kHz there is even an increase of more outside. It is then located at the bottom of the PCB raising
than 10 dB, so the degree of overdriving is highly frequency the use of SMD components to: recommended.
dependent and almost unpredictable. A calculation based on a 4. If no option is used for other microphones, the selected
linear noise behaviour is then not exactly what we need for the frequency characteristic of the MEMS microphone is subject
operation of the detector, but we make do with it. to correcting to obtain a straight frequency characteristic so
Of course, it would be better to adjust the frequency response that no other microphones are needed. Applying a digital
of the amplifier to the microphone. What should the calculation version will be a more sensible option than implementing
for the noise look like? If it should be possible to exchange the whole system in analogue fashion. By modifying the
microphones, then only a digital solution is considered. But firmware “in a flash” it is easy to make improvements,
back to calculus, now for the noise per source to the output. obtain different filter characteristics (e.g. a specific frequency
The noise of the microphone at a sound pressure is 94 dB then: band), or compensate for tolerance.
   
8 / (10 (48 / 20)) × (100 / 7.5) = 0.425 mV But even for the current version of the amplifier in the Bat
  DetectorPLUS, the question remains: how would you make your
For the resistor noise contributions we need to calculate with own test setup to determine the actual frequency character-
the parallel circuit of the two that determine the gain, i.e. the istic with any accuracy?
100 kΩ and the 7.5 kΩ ones. We leave out the resistor in the With this challenge we conclude Case Study 1 in the series
non-inverting input path, assuming it is replaced by a wire bridge: Analogue Electronics Design. In the next Elektor edition we will
  be filleting another subject ’in a completely analogue way’.
√(4 × 1.38 × 10-23 × 270 × 120000 × 6977) × (100 / 7.5) (200100-01)
= 0.047 mV
 
The opamp noise is amplified as with a non-inverting amplifier.
The noise of a TL06x is typically 42 nV/√Hz, so:

92 May & June 2020 www.elektormagazine.com


Explore the Raspberry Pi
in 45 Electronics Projects
Description:
Getting started with Raspberry Pi has
never been easier. Read the Third
Edition of Bert van Dam’s Explore the
Raspberry Pi in 45 Electronics Projects
for a thorough introduction to the
Raspberry Pi, handy programming tips
(e.g., Bash, Python 3, and Javascript),
and 45 compelling design projects.

Fully updated for the Raspberry Pi 4,


the book details a wide variety of design
projects:

• Drive an electromotor
• Temperature control
• Motor speed controller

O W6 •

Web server with CGI
And more!

N 31,4 er
s Take your Raspberry Pi-based projects
€ fo
rm
emb to the next level.

lektor

Read more on:


www.elektor.com/explore-the-raspberry-pi-
in-45-electronics-projects-3rd-edition
Inexpensive E-Scooter
How does Lidl’s “road approved”
300 euro E-scooter perform?
In many cities you can see small electric scooters all over the place. You can rent as well as buy them,
although at fairly high prices. Can much cheaper scooters also be used? An illustrated answer is given in this
article, using the example of a dirt cheap e-scooter spotted among the ’weekly deals’ promoted by a large
supermarket chain in Germany.

By Dr Thomas Scherer (Germany) Panning to Europe


All European countries have different
rules regarding these small scoot-
ers. While in many European cities the
whirring of the little speedsters has long
been part of everyday life (and pedes-
trians have become accustomed to this
Last year I was on the road for the first new “danger”), this is new territory in
time with a rental car in downtown Germany, as these vehicles were not
Tel-Aviv. As such I am not squea- registered until 2019. Of course, not
mish and adapt to the regional driving without corresponding bureaucratic
habits quite quickly. Different countries, regulations (see box on small electric
different driving style. But I hadn’t vehicles).
experienced this yet: in this bustling And, as befits the country of the “soon”
city in the Middle East there are not only to open capital airport BER, these
narrow streets and hardly any parking special regulations make the scooters
spaces, but in the densest traffic you more expensive, because first of all the
are overtaken and harassed by various Chinese production has to adjust to the
electric scooters flashing past on the German extra sausage. This is now the
Figure 1: The loot — after hunting the
left and right at the same time. Also case, and so the country’s largest food
e-scooter I still had time for some food
at the boardwalk, there are always the discounters, Aldi and Lidl, offered corre-
supplies.
carelessly left rental e-scooters. sponding models at a low price shortly
before Christmas 2019. Lidl kicked
Ergo: I also wanted to have one... things off and had the model “Doc Green
Small Electric Vehicles
(German regulations)
Since 2019, small electric scooters
have been legal and allowed for real
use in Germany too. But naturally
not without conditions:
• 20 km/h maximum
• not on sidewalks
• 14 minimum driver age
• no helmet requirement
• detachable ’lighting devices’.
• compulsory insurance
• General Operating License
• two independent brakes
• no indicators required
• a “bright bell” is needed Figure 2: The contents of the box — the folded e-scooter is waiting for the assembly of the
handlebars.

94 May & June 2020 www.elektormagazine.com


E-Scooter ESA 5000” in their program at
the end of November for an incredible
€299. Aldi followed shortly after with a
model priced at €279.
Thanks to the Internet, interested parties
were already informed in advance. That’s
why I knew that the Aldi model with one
charge would only get half as far as its
Lidl competitor, which is supposed to
cover 22 kms after all. I also knew that
with the model M365, there is a practi-
cally identical but more expensive and
non-DE approved device from Xiaomi [1],
and this Chinese company stands for high
performance and quality at low prices,
at least for smartphones. Even though
Lidl denied this connection, it was worth Figure 3: The “accessories” include the charger, Figure 4: Fully assembled e-scooter. That was
a few screws including an Allen wrench, and easy.
the extra cost to me, and therefore I
papers.
was already standing in front of the local
Lidl store in the dark at ten to seven on
the day of sale. And I was not the first!
In front of me there were already two
gentlemen of similar age, each armed
with a large shopping trolley and ready
to hunt through the corridors and capture
the coveted piece. By 7:00 am another
eight people were behind me. All of them
waited in the queue almost in a British
polite calm.
And the door opened and the race began.
In fact, the hunters in starting positions 1
and 2 had also loaded the first two scoot-
Figure 5: This is how the handlebars and Figure 6: Stable welding seams and folding
ers. And I got the third - of six. When I
“dashboard” look when switched on. The mechanism.
was back at the cash desk, a look back battery is flat.
showed that everybody was gone. Whew
— lucky! In Figure 1 you can admire my
hunting trophy.
handlebars to switch the scooter on. Then
First impressions the very bright, two-digit display lights Features
Once at home I transported the package up with the correct speed of 00 km/h • Road approval
to my electronics lab in the basement and the LEDs indicate the charge level of • Range: approx. 22 km
and of course I couldn’t resist: it had to the battery. Figure 5 shows the handle- • Speed: max. 20 km/h
be unpacked. After it was lifted out and bars in riding position. At this point my • Motor: rated power 350 W
freed from the foam pieces, the picture in zest for action was abruptly slowed down • Li-Ion battery rated at 36 V / 7.2
Figure 2 unfolded. The steering column because there wasn’t much power in the
Ah (259 Wh)
could be folded away and the handle- battery, and the manual demands a first
• Charging time: up to 7 h
bars still had to be fixed with four Allen full charge. The red paddle on the left is
• Charger: 42 V / 1.5 A
screws. Also a charger and paperwork the recuperation brake and the blue one
• Puncture-proof 8.5’’ air chamber
— especially the “data confirmation” on the right is a kind of thumb operated
— was there, as Figure 3 shows. The throttle. The handlebar grips are not tyres (Honeycomb)
latter is important because it corresponds rotatable. In the upper right you can see • Non-slip rubber pad on step board
to a “General Operating License” and the brake lever for the rear disc brake. • 2 independent brakes
the vehicle can only be insured on its Five hours later the battery was full. The • Front light: 20 lux, white reflectors
presentation. Completely assembled, first test drive could have started now. • Rear light: 10 lux (brake light), red
the scooter was standing in front of me Tried it out in the cellar: yes, it drives. reflectors
in all its glory just five minutes later Even then I noticed: there’s not that • Lateral: reflectors in yellow
(Figure 4). much power, even if it was still in eco • Bell (preassembled on handlebars)
But before starting the scooter, I had to mode to be on the safe side. But before
• Side stand
find out where to switch it on and what setting off, I wanted to know how well
• LED display for speed and charge
the LEDs etc. mean. According to the this electric scooter is designed.
status
manual you press the black button on the A look at the frame shows that the

www.elektormagazine.com May & June 2020 95


visible. From this it is clear that it is an
electronically controlled BLDC motor,
which makes it efficient and durable.
Figure 13 shows the charging socket,
which is protected with a rubber plug.
Again the great welding seams impress.

Test drive
After everything was reassembled, I went
out into the street. In the YouTube video
[2] you can admire my first, still cautious
driving attempts. At first I only dared
to drive in eco mode, which goes up to
15 km/h. And rightly so!
To make the scooter accelerate, you must
first push it to a speed of over 2 km/h.
Figure 7: Front wheel with hub motor and solid Figure 8: Rear wheel with disc brake and This is no problem, one push is enough.
rubber tyres. locking device for the folded down handlebars.
This little inconvenience has the advan-
tage that the high power consumption
when moving off is reduced and the
batteries last longer. Here we go and the
aluminium tubes are neatly welded only a thicker plastic cover at the bottom 15 km/h did not feel unsafe despite the
(Figure 6). The mechanism for locking (Figure 9). Thirteen screws later you small wheels. But then came the revers-
the handlebars also looks very stable. have it in your hand. Figure 10 shows ing, and as we all know, you have to
Figure 7 shows the front wheel. Lidl that it is simply sealed with a foam tape. brake for that. First of all: I didn’t break
talks about “8.5” air chamber tyres No big problem, because eBay offers anything...
(Honeycomb)” but I am not convinced. such aluminium covers for little money Of course I tested the left red lever
It reminds me more of normal solid tyres. in different colours for the Xiaomi M365 with the recuperation brake first.
In any case you don’t have to fear any (search for “Bottom Battery Cover Xiaomi Unfortunately it has a rather digital
loss of pressure. Figure 8 shows the M365”) and they should fit. In general, behaviour and the scooter brakes
rear wheel with the oversized, perfo- there are a lot of matching accessories abruptly and strongly. Since I was not
rated brake disc, rear lighting and license under the keyword “M365”. prepared for this, I almost flew across
plate holder. The grey rubber nipple at the handlebars. So I accelerated again
the top is used to lock the folded-down Figure 11 shows the most important and then decelerated with the rear brake.
handlebars. So you can carry the scooter thing: the battery. It is built from round The too you have hardly any control in
comfortably despite its weight of around cells (type 10s3p) and looks quite decent. the lever. The disc brake is much too
15 kg. You can find more details in the The brochure information is also correct. violent for my taste. If there would be
Features box. The battery is screwed to the frame from foliage, the rear wheel would be gone.
below and is easy to replace if faulty. So far, so hard.
Inner life The second most important thing is the There’s hardly any feeling of accelera-
As always, the innards are particularly electronics: Figure 12 shows that it is tion in eco mode. I would have imagined
interesting for electronics engineers. extra protected from moisture by a trans- 350 watts differently. But maybe the
So the scooter had to be screwed open parent plastic case. The six MOSFETs for full power only comes in normal mode,
right away. That’s easy, because there is a three-phase bridge circuit are clearly I thought. So I stopped, pressed the

Figure 9: The underbody is made of plastic and can be dismantled. Figure 10: Unscrewed cover with foam seal.

96 May & June 2020 www.elektormagazine.com


black button twice to switch over and
off I went. It may be that there is some
measurable difference between the
modes except the final speed, but I
could hardly feel it. After all, the Lidl
scooter runs its 20 km/h as promised.
That should be enough.

Conclusion
In general I was positively surprised by
the quality of the e-scooter. It is really
neat and stable. The battery doesn’t
disappoint either and you can fully trust
it to have the 22 km range - I haven’t
tried it though as I don’t like pushing.
The electronics also look good and the
lighting is bright and sufficient. That a Figure 11: The battery. Looks pretty decent.
scooter like this can be made for this
price amazes me.
I didn’t like the acceleration so much
though. That should be 350 W, really?
There is no real electric feeling - except
when recuperating. So to the biggest
shortcoming: the brakes are just too
violent. While the disc brake certainly
gets a bit smoother over time, recuper-
ation is simply too aggressive. Whoever
designed this has only used a part of his
mental potential.
All in all, I would come to a positive
overall assessment despite the brakes
taking some getting used to. The price/
performance ratio is already very good.
Nevertheless, I would strongly advise you
to take a test drive if you want to buy
such an e-scooter for yourself or your
Figure 12: The six MOSFETs are clearly visible in the encapsulated electronics.
offspring.
A good friend of mine tried out if this
scooter fits into the frunk (coinage from
front and trunk) of his brand new Tesla
Model X. Figure 14 proves that it does.
Martin would like to drive around town
on the scooter in case his Tesla takes a
break at a charging station. A good idea
and the scooter is certainly cheaper than
a wing mirror of his new electric vehicle.
But the Tesla is 12.4 times faster and
offers 885 times more power.
191251-03

Figure 13: Charging socket on the left side of Figure 14: Scooter in the frunk of a Tesla Model
the scooter. X (Photo: Martin Jepkens [3]).

Web Links
[1] Xiaomi Scooter: www.mi.com/global/mi-electric-scooter
[2] Test drive (YouTube-Video): www.youtube.com/watch?v=9UNWDpAYAoU
[3] Martin Jepkens: www.me-marl.de

www.elektormagazine.com May & June 2020 97


Steeped in Electronics
Lead-free soldering and EU regulatory zeal

By Ilse Joostens (Belgium)

When I was very young, in the early 1970s, we


lived in a row house with lead water pipes.
When I was five years old my family
moved into a brand-new house without
lead pipes, but with flooring that
contained asbestos and had been
treated with pentachlorophenol. I
must say that the latter sounds
really ghastly, and with all the
bad news now about things
we used to like so much, it
seems like a miracle that
I am still alive and able
to write this column.
The world has clearly become
a lot more dangerous since
I was young, and with the
introduction of the RoHS
regulations in 2006
the European Union in
particular apparently
found it necessary
to launch a major
crusade against the
use of a number of
hazardous substances
in consumer electronics. For some mysterious reason, lead is regarded as the
main culprit, and now it is even supposed to be banned from ammunition and fishing
weights.

Lead-free baking with lead-free solder. Strictly speaking, you could still use
If you do soldering, make repairs or build prototypes as a lead-based solder for your prototypes, but to avoid the risk of
hobby, you need not read any further, and you should get contamination I use only lead-free solder.
down on your knees and thank the gods that you are allowed The period shortly after the first Restriction of Hazardous
to use lead-based solder. If like me you put together commer- Substances (RoHS) regulation took effect in 2006 was fairly
cial products, you are out of luck and condemned to working dramatic for the electronics industry. Some lead-free processes

98 May & June 2020 www.elektormagazine.com


were not yet ready for use, and there was only limited experi- nents and SMD rework are still tricky tasks, leading to more
ence with the new methods. During that period I repeatedly failed components and half-finished products. In the very rare
woke up drenched with sweat after yet another nightmare cases where I work with lead-based solder, it’s always a relief.
about razor-sharp tin whiskers constantly growing between If you intend to get into electronics or you occasionally solder
the leads of fine-pitch SMT components, ultimately resulting something as part of your hobby, I can only
in smoke signals. recommend that you avoid lead-free solder.

Good soldering stations with active tips are


expensive, and actually there are no specific health
hazards from working with lead-based solder. Of course, you
shouldn’t eat it. Lead-free solders usually contain a somewhat
more aggressive flux, and the flux vapours are not especially
healthy. This doesn’t mean it’s okay to start smoking lead-based
solder like a chimney – that should be obvious.

Recycling
It’s also questionable whether banning lead from electron-
ics is really that much better for the environment. Instead of
the current cheap disposable electronics, it would have been
As far as automated better to aim for higher quality and more durable products.
soldering is concerned, This brings us to the recycling of products, and there as well
most of the problems the government busybodies and bureaucrats know how to
have been solved by now, make your life miserable. In most European countries there
and in practice the tin whiskers are organisations for recycling discarded devices and reusable
and other potential disasters have waste. In Belgium we have Recupel, Bebat and Fost Plus, among
turned out to be minor issues, although others. I am fully in favour of recycling, but association with
I have the impression that modern consumer the above-mentioned organisations is not only expensive but
electronics fails faster and more often than in the also involves a lot of paperwork. Fortunately, I’m not bothered
past. Of course, this could also be due to the quality of the much with this as long as I do not sell completely finished
components concerned. With the growing number of low-cost products or batteries and keep the use of plastic packaging
imports from Asia, it has systematically declined. within reasonable limits. From what I hear from colleagues
Unfortunately, manual lead-free soldering is still a bit of a and competitors in Germany, the situation in Belgium is not
challenge. And if we can believe the countless photos circu- so bad. Stiftung EAR, the German equivalent of Recupel, takes
lating on the Internet, soldering on computer motherboards is its role very seriously and has already imposed hefty fines in
very hard on the fingers, and the higher melting temperature of some cases. In Germany, rules are rules.
lead-free solder certainly doesn’t help. To see this for yourself, Despite all the regulations and prohibitions, components such as
just Google for pictures matching the search term “solder fail”, mercury switches and light-dependent resistors with cadmium
and be sure to have your burn ointment close to hand. sulphide (shiver!) are still readily available from Asian sources,
With my old soldering stations, soldering relatively large not to mention some potentially lethal products that do not
through-hole components on PCBs with plated-through holes comply with any standards but are still for sale in shops here.
was not exactly easy with lead-free solder, especially on solder Is this a sign of a double standard amongst our European
pads in or next to large copper planes. The irons were usually policy makers?
set to a temperature of 420 to 450 degrees C, and in some 200082-02
cases I needed two irons at the same time to get the solder
to melt. It’s hardly surprising that I went through solder tips
pretty fast. Although working with lead-free solder is a good
deal easier using modern soldering stations with interchangeable
active tips, my feeling is that soldering on large copper surfaces
is still not straightforward. Desoldering through-hole compo-

www.elektormagazine.com May & June 2020 99


Lab, Sweet Lab
A glimpse of The Holy Place —
no unauthorized entry.
By Eric Bogers (Elektor Netherlands)

In July 2019 Elektor organised a small


competition on their Labs website to
discover who has the nicest/untidiest/
most interesting/most remarkable
home lab. In this episode we present
the lab from Rainer Schuster, who will
be familiar to many Elektor readers.

Rainer’s lab gives an extremely organised


and tidy impression — something to be
envious of… He writes: “My ‘home lab’ is
nearly as old as (the German edition of)
Elektor itself — at least as far as the equip-
ment goes. It all started back in 1972 with
a multimeter and a power supply, and over
the years all the other equipment that you
can see in Photo 1 was added.” Most of the
test equipment were kit sets from the (long
gone) company RIM Electronic and from the
Heathkit, who, until the ‘80s, supplied justi- 2
fiably famous and excellent kit sets.
On the workbench you can catch a glimpse of
the project Rainer was working on when the photo was taken: which he made
a guitar amplifier for his son, based on the “Guitarix” app that for the occasion
runs on a Raspberry Pi 4. of the Elektor
But home-built equipment is also part of the lab, such as the Video Olympiade 3
“Transistor Curve Tracer” published in the February 2009 issue in 2017, where
of Elektor (Photo 2) [1]. he earned an
Photo 3 shows a couple of his own developments: the “HV honourable third place with his
Power Supply / Tube Curve Tracer” [2] (top) and the “Electronic description of a few of the infamous ‘joke circuits’ Elektor
Load for DC and AC” [3] (bottom), both of which have been magazine used to publish in the annual Summer Circuits issue.
posted on the Elektor Labs website.
And finally, Rainer’s lab can also be seen in the video [4] 200086-03

We Links
[1] Transistor Curve Tracer: www.elektormagazine.com/magazine/elektor-200902/18980
[2] HV Power Supply / Tube Curve Tracer:
www.elektormagazine.com/labs/hv-power-supply-with-tube-and-semiconductor-curve-tracer
[3] Electronic load for DC and AC: www.elektormagazine.nl/labs/electronic-load-for-dc-and-ac
[4] Video: www.youtube.com/watch?v=2f75lK12Wjo&list=PL2a34OA-WuybkArjgAnXiIFqUc3KYf19A&index=4

100 May & June 2020 www.elektormagazine.com


review
The PeakTech 6080 A
Lab Power Supply
A neat lab PSU for not much money
By Dr Thomas Scherer

It’s well known that electronics engineers never have enough power supplies. I’m no exception to this rule,
as you can see from a photo of the home lab in my basement. The neat PeakTech 6080 A power supply is
unusual amongst all the PSUs on the market today. It has been designed using linear technology with a
traditional power transformer. The result is a quiet output voltage, highly accurate displays and all for not
much money at all...

It’s well known that electronics engineers never have enough Power Supply [1] from 1980! 40 years old and still accurate
power supplies. I’m no exception to this rule, as you can see to 0.1%, good design is the key. Next in line is a relatively
from a photo of the home lab in my basement. It all looks a high-impedance mains voltage source with safety insulation
bit squashed up but I’m sure I could make room for just one and a load capacity of around 60 W, it’s not beautiful, but it’s
more… The small PeakTech 6080 A lab power supply offers practical and saves lives.
power and accuracy for a very reasonable price. The digital lab power supply delivers a lot of power with a
Actually, the home lab is already quite well equipped with power maximum of 60 V at 8 A — this one is obviously not homemade!
supplies. A 12 V 9 A unit (far right) is ideal to power small Now the PeakTech 6080 A has been added to the lineup, it
low-voltage drilling/grinding machines such as a Dremel or only delivers 3 A at 15 V max, but stands out because of its
Proxxon etc. You can also see the homemade Elektor Precision other features.

Unboxing
The PeakTech PT 6080 A power supply did not reach me via the
normal route that other parcels have taken when they arrive
at my door. This time I got a call from a neighbour who lives a
few blocks away. He said his parents had seen some packages
fall from a passing mail van carrying parcels and my name and
address was on one of them. It was Christmas Eve so suspi-
cious of a prank I asked if it was gift wrapped and maybe,
was the van being pulled along by… reindeer? He remained
serious so I thought it would be best to go and investigate.
Sure enough it turned out to be the PT 6080 A power supply
unit I had recently ordered. The package was a bit scuffed but
not badly damaged.
You may well be wondering the significance of this anecdote: In
Figure 1: The lab power supply is protected by thick foam packing. fact it turned out to be a good drop-test for the power supply,

www.elektormagazine.com May & June 2020 101


Figure 2: Front and rear view of the PT 6080 A (Image: PeakTech). Figure 5. Output voltage noise levels under various conditions.

the packaging with its internal foam cushions (Figure 1) did Precision on display
an admirable job of protecting the unit. It survived unscathed What really interests me with regard to power supplies is the
and is fully functional. accuracy of the displayed voltage and current levels. I also have
  a digital power supply unit, where the voltage and current are
The unit is 80 x 160 x 225 mm (W x H x D) and its layout is set digitally using two rotary encoders. This switch between
more ‘portrait’ than ‘landscape’ (Figure 2), which takes up coarse and fine adjustment (in a ratio of 1:10) can be toggled
less bench space. The thick, heavy heat sink on the back looks by pressing the knob. Budget priced digital power supplies
well proportioned to keep the power components cool. It is the usually only show the value of what has been setup, not what
first indication that this power supply unit is designed using is actually coming out of the sockets. As a result, there are
more traditional, linear technology. This type of supply needs always small discrepancies in the range of 100 mV or a few
to dissipate high levels of power when delivering high current tens of milliamps in the displayed value and the actual value.
at low output voltages. The second indication of the chosen Cheaper digital power supplies often cut costs by omitting the
technology is the unit’s weight: 2 kg is relatively heavy for a digital voltmeter chip thereby making the displayed values
45-W power supply. This indicates there is an iron or ferrite- less representative.
cored transformer inside running at mains frequency. Switched- The PT 6080 A is different. Instead of encoders, normal poten-
mode supplies will use smaller, lighter transformers switching tiometers are used here. The ‘gear ratio’ from coarse to fine
at a much higher frequency. adjustment is about 1:7. For me, the analogue setting adjust-
  ments took some getting used to. Unlike digital power supplies,
The lab power supply has an output voltage range adjustable you do not immediately see what you are setting. The applied
from 0 to 15 V via its two safety 4-mm banana sockets on the voltage and current flow are measured digitally and average
front panel which accept shrouded or standard banana plugs. A/D converter chips can manage about three or four measure-
Output current limit can be set from 0 to 3 A using the ‘A’ coarse ments per second so there is always a slight delay between the
and fine adjustment pots. Output voltage can be set similarly pot movement and the displayed values. I wouldn’t say this is
using the ‘V’ coarse and fine pots. Two four-digit displays bad, just different from the digital lab power supply I’m used to.
show both the output voltage and current level. Two LEDs Figure 3 shows an impressive aspect of this power supply:
labelled ‘C.C.’ and ‘C.V.’ indicate whether the unit is operat- The displayed values are almost identical to those of shown
ing in constant current or constant voltage mode. Figure 2 on my multimeter. There is a discrepancy of 10 mV = 0.07 %
shows the C.V. LED lit. When the current limit is reduced from for the voltage and 0.3 mA = 0.08 % for the current (the
its maximum setting the C.C. LED will be lit instead. deviation is similar at 3 A). This is surprising, I calibrated the

a b

Figure 3: Displayed value vs DVM measurements (voltage above, current below). Figure 4: Maximum voltage (a, CV) and
maximum current (b, CC).

102 May & June 2020 www.elektormagazine.com


multimeter against a 0.1 % accurate reference voltage source
before I started measuring. The PT 6080 A is therefore much
more precise than the manufacturer’s specification of 0.5 %
±5 digits and you can have confidence in the displayed readings.
I certainly didn’t expect that!

Noisy or quiet?
The next important aspect is the electrical ‘cleanliness’ of the
output voltage under load. A low-power linear lab PSU would
not be chosen to primarily power digital electronic circuits. It is
more suited as a power source for analogue, audio frequency
applications or RF circuits. For these applications it is import-
ant to provide a supply free from noise spikes and interfer-
ence. Except for very expensive laboratory equipment, the
output voltages supplied by digital lab PSUs are almost always
contaminated with interference and noise signals related to
the switching frequencies (and harmonics thereof) used by
the switched-mode controller. PSUs based on linear regulators
should fare better in this respect, is that true of the PT 6080 A?
The manufacturer states that the residual ripple of the voltage
is 0.5 mVrms. Figure 5 shows four screenshots of output voltage
waveforms under different load conditions. The sensitivity (2 mV/
graduation) and time base (10 ms/graduation) are the same for all
of the images. Noise and hum in CV mode are within the specified
range both under no load (a) and loaded (b) output conditions.
The output voltage is not quite as good when in CC mode. Here
the ripple is around 2 mVeff regardless of the load. The clearly
visible low-frequency 128 Hz (c) or 171 Hz (d) fundamental
is not a harmonic of the mains frequency so is not likely to be
mains hum.

Under the covers


To check out the build quality I removed six screws holding
Figure 6. Inside the PT 6080 A is a mains transformer, power board and
the sheet metal cover on and took a look inside (Figure 6).
controller board with SMDs.
The heavy toroidal transformer takes up a lot of the internal
volume. It uses a tapped primary winding so it can run on 230 V
or 115 V mains. A 30-V winding with a centre tap supplies
the front control/display board (C). On the back is the circuit well designed. The output voltage has no measurable mains hum
board with a bridge rectifier made from four 5-A diodes and and is well regulated, showing very little drop under load.  The
a 4,700 µF/50 V electrolytic capacitor to reduce the ripple. A output voltage noise level in CV mode is good and the power
power transistor is mounted on the back heatsink area. The supply does not get particularly hot in use, even under high,
small black box to the right of the diodes is a relay, which can continuous load conditions. This is mostly due to the low-volt-
be heard switching when the output voltage is adjusted around age switchover by the relay, which is a feature not often seen
7.5 V. Below this threshold, the relay switches a transformer in linear bench power supply units in this price bracket. The
secondary winding tap of 12.5 V to the rectifier, above this unit is also rated as short-circuit proof.
threshold it switches to the 21.5-V tap. This mechanism reduces All in all I was impressed by this small lab power supply and
the power dissipated in the output transistor when the PSU would give it a ‘recommended’ rating.
is operated at high current with a low voltage output setting. 200009-03

To sum up
By choosing the PeakTech PT6080A (available from the Elektor
4 sale @ www.elektor.com
Store for less than €60) you will be getting a good quality, low
noise power supply with digital displays showing impressively ªPeakTech 6080 A DC Lab Power Supply
accurate output voltage and current readings. The electronic www.elektor.com/19111
components and PCB are of good quality and the unit layout is

Links and literature


[1] Elektor Precision Power Unit (1980): www.elektormagazine.com/magazine/elektor-198009/44524/
[2] PT 6080 A, Data: www.peaktech.de/productdetail/kategorie/acdc-stabilisierte-labornetzgeraete/produkt/peaktech-6080-a.html

www.elektormagazine.com May & June 2020 103


welcome in your
ONLINE STORE Elektor Bestsellers
1. DVD Elektor 2010 through 2019
www.elektor.com/19194
EDITOR’S CHOICE

JOY-iT Joy-View 13 Touchscreen


It’s not easy to find a small, high-quality monitor that is con-
veniently portable – the options are fairly limited. The Joy-
View 13 makes the choice a lot easier, and thanks to the pres-
ence of both HDMI and USBC ports, it can be connected to
virtually all modern devices.
The Joy-View 13 portable touchscreen monitor is a nicely fin-
ished unit that provides excellent video and can be used in 2. Explore the Raspberry Pi in 45
many applications and with many different devices Electronics Projects (3rd Edition)
www.elektor.com/19190
thanks to the built-in capacitive touchscreen, the versa-
tile connection options and the variety of power 3. Raspberry Pi 4 B (2 GB)
supply options. If you are looking for a moni- www.elektor.com/18965
tor that is compact and easily portable, the Joy-
4. Programming with Node-RED
View 13 is an excellent choice. And if you would
www.elektor.com/19224
like to have something a bit larger, you can also
opt for the 15.6-inch version of this monitor, 5. Microcontroller Basics with PIC
the Joy-View 15. www.elektor.com/19188

6. Raspberry Pi 4 B (4 GB)
Harry Baggen (Elektor Labs) www.elektor.com/18964

7. Elektor Raspberry Pi Electronics Kit


www.elektor.com/19162 | www.elektor.com/19163 www.elektor.com/19187

Explore the Raspberry Pi in JOY-iT JT-RD6006 DC Sony Spresense Main Board


45 Electronics Projects (3rd Edition) Power Supply Bundle

NEW

The completely revised 3rd edition describes 45  exciting This bundle (available exclusively from Elektor) contains Spresense is a compact development board based on Sony’s
and compelling projects, such as a flashing lights, driving the programmable laboratory power supply JT-RD6006, an power-efficient multicore microcontroller CXD5602. It allows
an electromotor, processing and generating analog signals, industrial power supply unit (60 V, 6 A), a large aluminium developers to create applications in a very short time and is
a temperature control and a lux meter. More complicated housing and a plug-in WiFi module which enables the supported by the Arduino IDE as well as the more advanced
projects are also included, such as a motor speed controller, a JT-RD6006 to be controlled by other (mobile) devices NuttX based SDK. The main board uses a processor developed
web server with CGI (Common Gateway Interface), and client- via wireless connection. The bundle will be supplied in a by Sony for IoT and sensing applications. The main board can
server applications. practical hard case. be operated alone or with the extension board.

Member Price: €31.46 Member Price: €175.46 Member Price: €71.96

www.elektor.com/19190 www.elektor.com/19211 www.elektor.com/19233

104 May & June 2020 www.elektormagazine.com


shopping books cd/dvd diy projects development tools sale

Programming NEW
with Node-RED
Produced by IBM, Node-RED is an open-source visual editor for
wiring the Internet of Things. Node-RED comes with a large number
of nodes to handle a multitude of tasks. The required nodes are
selected and joined together to perform a particular task. Node-RED
is based on flow type programming where nodes are configured and
joined together to form an application program. There are nodes
for performing complex tasks, including web access, Twitter, E-mail,
HTTP, Bluetooth, MQTT, controlling GPIO ports, etc. One particularly
nice aspect of Node-RED is that the programmer does not need to
learn how to write complex programs.
The aim of this book is to teach how Node-RED can be used in
projects. The main hardware platform used with most of the projects
in this book is Raspberry Pi 4. Chapters are included to show how
Node-RED can be also be used with Arduino Uno, ESP32 DevKitC, and
the ESP8266 NodeMCU microcontroller development boards.

Member Price: €33.75


www.elektor.com/19224

Microcontroller Basics with PIC The State of Hollow State Audio Tactigon ONE – Gesture &
Motion Controller with AI

In this book the author presents all essential aspects of Audio tubes are currently experiencing a comeback, especially The Tactigon ONE is the ultimate wearable board,
microcontroller programming, without overloading the in the music and high-end audio industry. This new book programmable with Arduino IDE. It features GPIOs, UART, an
reader with unnecessary or quasi-relevant bits of information. provides answers to the following questions, among others: Do integrated battery recharge system, a fast microcontroller,
Having read the book, you should be able to understand as tubes produce better sound and how do hollow-state circuits and Bluetooth LE onboard! Measure linear and angular motion
well as program, 8-bit microcontrollers. The introduction work? How do you design hollow-state audio circuits? Can with a 3-axis gyroscope and 3-axis accelerometer. An extra
to microcontroller programming is worked out using you recreate some of the classic hollow-state audio devices 3-axis magnetic sensor provides more precision. The high-
microcontrollers from the PIC series. for modern listening rooms and recording studios? How can speed microcontroller unit and Arduino SDK allow for complex
you intelligently modify hollow-state amplifiers to your taste? sketches execution.

Member Price: €31.46 Member Price: €31.46 Member Price: €71.96

www.elektor.com/19188 www.elektor.com/19170 www.elektor.com/19218

www.elektormagazine.com May & June 2020 105


Beyond Electronics

A Big Challenge
Safe products in the IoT era
By Tessel Renzenbrink (The Netherlands)

Seat belts, airbags, crush zones, speed limits and combatting drunk driving – over many decades,
technological innovations and regulations have made cars ever safer. The same applies to other consumer
products. We buy them with confidence and trust that they are safe. But the advent of the Internet of Things
(IoT) opens a new Pandora’s box. With more and more products being equipped with electronics, software
and network connectivity, we are exposed to new dangers and risks. There are plenty of examples, such as
networked toys that can be used to spy on children or vehicles with control systems that can be hacked and
taken over remotely.

Professor Ross Anderson and his colleagues have investigated of both worlds. For example, consider phones versus vehicles.
which measures are necessary to combine traditional product The firmware and operating systems of phones are typically
safety with the advent of the IoT. They did this on behalf of the supported for about three years. After the support period ends,
European Commission. The EU is working on new legislation a phone becomes unsafe because the vulnerabilities of the
to ensure product safety in the future. They asked Anderson software are no longer corrected. People are forced to replace
to identify what is necessary for this. Anderson, a profes- their phones, even though the hardware is still perfectly okay.
sor of security engineering at Cambridge University, carried We need to make sure that this approach is not followed in the
out the study with his colleagues Eirann Leverett, Senior Risk automotive industry in the future, says Anderson.
Researcher, and Richard Clayton, Security Researcher. The However, lifetime maintenance comes with its own challenges.
report with their findings was published in 2017 [1]. Suppose a manufacturer is required to support a particular
vehicle model for at least 20 years. A software engineer who
Trilemma writes a program for a vehicle with a planned market launch in
Anderson and his colleagues concluded that we still have a 2022 will have to take into account that the code must continue
long way to go. The crux of the issue is that the way we ensure working until 2042.
the safety of physical products is fundamentally different from Complexity is also a challenge. The idea of the IoT is that
how we ensure the safety of digital technologies. Products are devices can communicate with each other and take action
tested and inspected before they are put on the market, and independently. For example, autonomous vehicles that exchange
this is assured by a safety certificate or an approval mark. information with the road infrastructure or refrigerators that
If there are significant changes to the product, it must be do their own shopping. From a safety perspective, this means
certified again. By contrast, the safety of software is essen- that testing devices on their own is no longer sufficient. It is
tially dependent on changes. Software is constantly monitored also necessary to examine the risks arising from the interac-
and regularly revised with patches and updates. Anderson tion with other devices.
addressed this in more detail in a presentation on their study
at the Chaos Communication Congress (CCC) in December Recommendations
2019 [2]. He called this the ‘trilemma’ of IoT products. If Product safety in the IoT era is a complex issue that does not
you stick to pre-market certification, you cannot modify your have any simple solutions. In their report to the European
software, which means your product is unsafe. If you modify Commission, the three researchers made several recommenda-
your software, you lose your certification. And if you combine tions. The main recommendation is to establish a new European
certification with updating, which means going through the agency, dubbed the European Safety and Security Engineering
certification process again after each software update, the Agency (ESSEA). The ESSEA must have the technical exper-
costs go through the roof. tise necessary for tasks such as developing standards and
informing policy makers. In addition, it must house a central
Lifetime and complexity database holding information about software vulnerabilities,
Traditional products and digital services each have their own failing components and errors in system integration. Presently
characteristics, which are now being combined. According to this sort of information is held by a variety of agencies and
Anderson, we need to avoid ending up with the worst features companies. Bringing this information together would enable

106 May & June 2020 www.elektormagazine.com


people to learn from each other
and avoid making the same
mistake twice.
Another recommendation is
that manufacturers that add
networking capabilities to their
products must ensure that it is
possible to perform software
updates.
In addition, the EU should
amend a number of existing
directives and regulations to
accommodate the new devel-
opments. The Product Liability
Directive, for example, should
be extended to cover digital
services. Under the provi-
sions of the current directive,
a manufacturer of navigation
devices can be held liable for
errors, but the makers of Google
Maps cannot be held liable.

The EU as a line of
defence against an
Internet of Trash
During the presentation at the
CCC, Anderson commented
that has proven difficult to
get the recommendations
implemented. There are many Photo: Gabor Kiss safety door. CC BY 2.0 https://www.flickr.com/photos/-nevi-/5404057758/
different parties involved, each
with their own interests. For
example, Facebook and Google
lobbied against the proposal to subject digital services to Union. However, in a related scientific article they write that
existing liability regulations. However, a number of things their hope is fixed on the EU: “The EU is already the world’s
have been achieved since the publication of the report. For main privacy regulator, as Washington doesn’t care and nobody
example, Regulation No. 2019/771 has been adopted, which else is big enough to matter; it should aim to become the main
stipulates that consumers of products with digital elements safety regulator too — or risk compromising the safety mission
have the right to updates for at least two years, or longer it already has.” [3]
if that can reasonably be expected. The latter means the 200066-02
products that are considered to last longer, such as washing
machines, should also receive updates for a longer period.
The enormous task described by Anderson, Leverett and Clayton
to ensure the safety of IoT products in the future contrasts
sharply with the slow decision-making process in the European

Links and literature


[1] Eireann Leverett, Richard Clayton, Ross Anderson, Editor G.Baldini, Standardisation and Certification of Safety, Security
and Privacy in the ‘Internet of Things’, European Commission, Brussels, Belgium, 2017
[2] The sustainability of safety, security and privacy [video]. Presentation by Ross Anderson at the Chaos Communication
Congress in Leipzig, 28 December 2019. :
https://media.ccc.de/v/36c3-10924-the_sustainability_of_safety_security_and_privacy#t=1397
[3] Eireann Leverett, Richard Clayton, Ross Anderson, Standardisation and Certification of the ‘Internet of Things’, 2017

www.elektormagazine.com May & June 2020 107


RETRONICS

Elektor 1.2 GHz Multifunction


Frequency Meter (1992/93)
Crossing the magic 1 GHz border
By Jan Buiting (Elektor Retronics Editor)

The project called “High Frequency Counter” dates back


to December 1992, early 1993 as far as the three article
instalments go in Elektor magazine. Browsing the back
issues, it was a time when the major projects developed
in the lab reached a certain level of industrial design and
ergonomics, meaning the enclosure and the front panel
layout were important factors in the whole design, as well as
software control, easy testing by the user, and an option to
buy the project as a kit of parts with a book complement.

As with many instalments I’ve made so far for the Retronics taking a 10-foot flight out of the window and a hard landing,
series, the subject was not chosen randomly from the vast so no need for me to “dumpster dive” at that time.
Elektor archive stretching back to No. 1 from 1974. Rather,
it’s because the item has survived Elektor’s unstoppable Not lost in translation
custom of consigning “hardware” to the bin after a few years, The discrepancy between the working title of the project and the
especially lab prototypes. In this case, the bin was actually a actual magazine article title “1.2 GHz Multifunction Frequency
large dumpster placed under the lab windows at the former Meter” in Elektor magazine is indicative of the steadfastness of
Elektor Head Office in Beek, Holland, back in July 2006. As with the four ‘language groups’ working at Elektor HQ and always
a few more instruments I’ve been able to describe in Retronics bending over backwards to localize their ‘national’ edition on
articles, I was able to prevent the subject of this instalment from the basis of material supplied by predominantly Dutch and

108 May & June 2020 www.elektormagazine.com


German lab staff. The job extended considerably beyond plain (anyone have one? — let me know) was a power-hungry,
translating. 250 MHz, TTL component jungle compared to the lightweight,
The German author of the project, Bernard C Zschocke, origi- portable version from 1992 which featured an 80C32 micro-
nally submitted his project as “Hochfrequenz-zähler”, which controller, a U664 (or equivalent) dedicated prescaler, an LCD,
having passed the lab’s German-English dictionaries, eventu- and battery powering. The upgrade was substantial, justified
ally ended up on the instrument front panel decal as “High and a good reflection of what could be built by hobbyists back
Frequency Counter”. With hindsight, not the best name for in 1993 with a good chance of success. And crossing the magic
the instrument as it expresses neither what’s being ‘counted’ 1 GHz barrier!
and how ‘high’ the frequency went. So at least in the English Remarkably and perhaps wisely, the 1992 design was not
department where I worked, the article series was duly headed: compared in the articles to any professional instruments avail-
1.2 GHz Multifunction Frequency Meter. I remember discuss- able back then like HP and Tektronix. Still, the project came
ing with some editorial and lab colleagues at that time that with impressive specifications, a few of which I’ve reproduced
‘frequency counter’ is a repeatedly seen and heard misno- in the Concise Specification textbox.
mer. You cannot count ‘frequency’ — only occurrences (like
pulses) per unit of time (like seconds). In vain, the wording Is this vintage?
“Frequency Counter” slipped through and appeared in capitals Looking at the 1.2 GHz Multifunction Frequency Meter schematic
on the instrument front panel. in Figure 1 (reproduced from a scan) I could not suppress a
The author’s name was a tongue twister with its bewilder- tendency to “recast” the design using components from the
ing sequence of four consonants in a row and it got typo’d year 2020. The use of shaded sections in the original schematic
and mangled many times except
of course in Elektor ’s German
department. Fortunately, none of
these mishaps reached the Elektor
audience. Rumour has it though that
for the German edition only, the
author had requested the pseud-
onym “Urban” which at one point
got mangled to ‘U-bahn’ by a certain
editor.

Back in 1993
Almost 30 years ago, the basic
course a project would follow
towards final publication in Elektor
magazine and PCB sales was not
fundamentally different from today.
Authors would send project submis-
sions in a stamped envelope and
patiently await the Go/No-Go/Maybe
Later verdict from the editorial team,
given by post or telephone. After a
(negotiated) ‘Go’, the project would
be presented as an engineering draft
to the lab team who were supposed
to make the electronics repeatable
for home construction (or even
kitting), design a matching PCB,
and create a software product like an
EPROM. In the case of the 1992/93
frequency meter, the process took
approximately a year although Mr
Zschocke’s original material including
his writeup was quite good, requiring
little ‘post engineering’ and ‘editing’
in Beek.
According to part 1 of the article
series, the project was “a worthy
successor to our famous 1985 Figure 1: The schematic of the 1.2 GHz Multifunction Frequency Meter reveals a mid-1990s-style
microprocessor-controlled frequency marriage between a 40-pin DIP cased microcontroller (here, a 80C32) and discrete electronics. With
meter, thousands of which are in use so much functionality carried out by software, the resulting BOM was remarkably small. (scanned
all over the world”. That 1985 project reproduction)

www.elektormagazine.com May & June 2020 109


The 80C32 was a big thing at that time, coming from
Elektor’s apparent infatuation with the Intel 8051/8052
series and derivates which remained popular for at least
two decades especially in Germany. The ‘C32 was a
low-power CMOS MCU using external (EP)ROM and a
small amount of internal RAM, hence excellent for
hobbyists. Countless projects of the more serious
level that appeared in Elektor had the winning
combination: 80C32 + 27C128/256/512, the
latter available ready-programmed through
the Elektor product service (EPS).
For the GHz prescaler chip, several alternatives were
mentioned in the article, including Plessey’s SP4731 and
SP4732, Siemens’ SDA4212, Telefunken’s U664B, and Philips’
SAB6456. Excepting the SP4732, all tended to oscillate causing
random readouts on the display especially on no or too low
input signals. This is normal however and a result of the basic
Figure 2: A look inside the opened case
operation of these chips. Come to think of it, I’ve been ignor-
of the 1.2 GHz Multifunction Frequency Meter.
Note the metal screening around the prescaler area ing the random readouts of my home-built 600 MHz counter
where frequencies up to 1.2 GHz may appear (fingers crossed). with an 11C90 prescaler chip and considered it a sign of utter
sensitivity, not unlike a reflex receiver on the border of “going
Mexican” i.e. self-oscillation. This design did have a 15 dB
wideband preamp ahead of the prescaler, a thing I believe the
and the general quality of presenting a complex design are a Elektor 1.2 GHz counter is lacking.
great help. As a mental exercise only:
The case for a case
• 80C32, EPROM, IC5, IC3 (MCU section) ž Arduino, ESP32 A good deal of effort went into the design of a professionally
• K12, IC6, T2 and surroundings (pseudo RS-232) ž a USB looking case for the counter, including the “three-colour” front
port panel adhesive which was available ready made from EPS. As
• 7805 (supply) ž some recent LDO regulator you can see from the picture of the opened case in Figure 2,
• 9 V supply ž 6 V supply the PCBs fitted perfectly in the Vero case (with two shades of
• LCD ž OLED grey). A full page in the article is dedicated to the front panel
• BAT82’s ž HP28xx ultra low capacitance diodes drilling template. The PCBs were:
 
• Main board (with a cutout for the PP3/6LR61 battery
holder)
Concise Specification • Pushbutton board (for Digitast switches)
Measurement modes: • LCD board (Philips LTN211-F10, replaced later by Sharp
• Frequency meter: 1 mHz to 1.2 GHz LM16A21 and Hitachi LM016L)
• Period: (1/frequency): 1 ps to 4,000 s  
• Revolution counter: 0.001 to 4×106 rev/min The part covering the construction the project at home from
• Event (pulse) counter: 1 to approx. 4×109 individual parts and pieces is of a length and detail you’d be
• Zero counter: 1 to 4×109 hard pressed to find in today’s electronics press dominated
  by embedded platforms. The prescaler area on the board, for
Generator modes: example, had to be fully screened with tin plating, including
a cover. Looking at Figure 2 again, the prescaler IC is seen
• Timer: 1 µs to 4,000 s
inserted in an 8-pin DIL socket, probably with component
• Pulse generator: 8,500 s (0.117 mHz) to 4 µs (250 kHz)
exchangeability in mind. I would have expected to see this
• Duty factor: 1:1 to 1:4×109
very high frequency chip soldered directly onto the board to
• Period number: 1 to 4×109
minimize stray capacitances. Also, those twisted wires between
 
the BNC socket and the ‘A’ input of the board are poor practice
User-defined settings:
to say the least (the highest frequency available in the labs
• Single/continuous measurement at that time was 512.000 MHz — and it still is today from a
• Floating gate time vintage HP 8640B RF generator).
• Intermediate measurement result display
• Period analysis (accurate measurement of low frequencies Testing and aligning
at short gate periods) The test procedure for the project reflects its ‘early embed-
• Quiescent level ded’ nature where an instrument’s firmware has a number of
• Pulse polarity routines built in to interrogate and test hardware components,
• Sounder on/off and show the results on its own display. The overall test routine
can be divided into three main groups

110 May & June 2020 www.elektormagazine.com


Figure 3: You can’t test everything by poking bits and bytes around! In Figure 4: The GHz Counter project bundle sold by Elektor Germany and
some cases, old fashioned hardware can come to the rescue. Here, a some kit suppliers comprised a booklet and a very comprehensive kit of
single 74HCT74 chip acts both as a logic signal generator and a logic parts. The bundle first appeared in 1995 i.e. well after the publication of
probe with audible output. Wow! the GHz counter in Elektor magazine.

• LCD project. The Elektor staff working in Aachen initiated to have


• Main board kits put together by an advertiser in their magazine (probably
• Serial I/O Geist Elektronik) and sell it under the Elektor Germany brand,
  along with a book instead of photocopied articles. Again, this
Assuming the CPU, EPROM, LCD, xtal and address latch function was a Germany-only undertaking and it may have been the first
properly, the test routine ‘menu’ is kicked off by pressing the go of Elektor Germany’s team at selling a bundle (or package)
MENU or ENTER key at power on, and the same key combination based on a design published in a magazine article. Today, the
to leave the menu (BREAK). The three subsystem tests look whole publishing house is doing it 24/7 in four languages.
pretty exhaustive and must have been a good aid to localizing The package, pictured in Figure 4, is rare today and appar-
trouble in such a complex circuit. ently around one hundred were sold, which compares favour-
Although I find it hard to imagine, some users of the instrument ably against 2000 or so of the individual boards, EPROMS, and
may not have had an oscilloscope available to aid in testing the front panels. The white box contains the kit of parts to build
counter. Not having a PC with an RS-232 port wasn’t as bad the counter, that’s including the predrilled case, EPROM, front
though as the relevant test covered a more or less optional panel adhesive, and all mechanical parts. The Heathkit times
feature of the counter: remote control and readout.
The simplicity and old-school design of the auxiliary tester that
appeared in the magazine I found worthy of reproducing here in
Figure 3. A single 74HCT74 bistable does the job, acting as a
simple pulse source and an audible ‘digital probe’ at the same time.
Like you I wondered about the frequency stability and resultant
resolution of the instrument and was saddened by the expected
“it all depends on the 12 MHz crystal”. In the prototype a cheap
computer xtal was used. The article says: “[adjusting the central
oscillator] … is best done by applying a known, high-precision
test frequency to the meter, and adjusting the trimmer capacitor
C2 until this frequency is displayed”. With 28 years hindsight
the CPU should have been clocked at 10 MHz which would have
allowed referencing from a professional frequency standard, an
xtal oven, or even Elektor’s own 10 MHz Frequency Standard. In
today’s money it would have been a GPS disciplined oscillator.

The Full Monty Figure 5. Kit contents (1995). For the sake of authenticity, no attempt
About one and a half years after the magazine publications, the was made to empty all paper bags containing the electronic components
EPS board sales indicated further commercial potential of the inside.

www.elektormagazine.com May & June 2020 111


all applauded and the result
was printed on a full page
in part 2 as well as supplied
as a foldout sheet tucked
in with the German book.
Figure 6 shows an attempt
at reproducing the originally
400 × 260 mm sized sheet
printed on glossy paper (!).

Tantalum Tantrum
I tried to make the instru-
ment work by inserting
a fresh 9 V battery in the
holder at the underside,
and powering up with the
small slide switch. Nothing
happened and when I
probed the + supply wiring
at a few points with a DMM I
found about +3 V behind the
on/off switch. It was obvious
that something was loading
Figure 6. Alongside a description in words, a drawing was made back in 1993 of the counter’s impressive menu the battery excessively and
structure and user options. The original was sized at 40 × 26 cm and came as a foldout sheet. I immediately suspected one
or more of the electrolytic
capacitors on the supply
relive for a moment. The contents of the package I safeguarded rails, notably the tantalum ones C14 and C17. With hindsight
back in 2006 is untouched and I was delighted to even find a I was happy I used a battery for a few seconds only and not a
length of solid, bare “you-never-know” wire and pieces of sheet benchtop supply as it would have blown out a few componets.
metal to assemble the prescaler screening. Resistors, sockets, I intend to do the necessary repairs to see if the instrument
ICs, pushbuttons, the display, BNC sockets, the programmed actually works — I’m confident.
EPROM, it’s all there and neatly packaged mostly in small, The three instalments describing the 1.2 GHz Multifunction
white paper bags (Figure 5). Frequency Meter are in Elektor’s online archive and accessible
The book in the package is another perfect companion. It packs as pdf files to Green and Gold Members [1][2][3]. The article
all three instalments of the article (December 1992, January instalments are also on the Elektor 1990s DVD. Please note
and February 1993) into a size just over that of the actual that the project is no longer recommended for new construc-
counter once assembled in the Vero case. tion as several parts are no longer available.
190382-C-01
Menu please!
The copy preparation of part 2 of the article grinded to a halt
and ran into some delay when a desk editor of the Dutch
department at Elektor said that the instrument’s menu should
be elucidated and illustrated in proper detail. So far, most of
the lab staff had not selected much from the menu beyond
Retronics is a regular section
‘Press Enter to Continue’ let alone ventured into the myriad
covering vintage electronics
of options hidden deep in the software. So, Dick Lubben at his
including legendary Elektor projects.
quiet desk in Beek spent about two working weeks charting
Contributions, suggestions and requests for instalments are
and documenting the counter’s software structure to the finest welcome, please telegraph the Retronics Conservator on:
detail, culminating in an enormous sheet showing every option, [email protected], subject: Retronics (STOP).
display text and error code imaginable. It was a fantastic feat,

Weblinks
[1] 1.2 GHz Multifunction Frequency Meter, part 1. Elektor Electronics December 1992:
www.elektormagazine.com/magazine/elektor-199212/32728/
[2] 1.2 GHz Multifunction Frequency Meter, part 2. Elektor Electronics January 1993:
www.elektormagazine.com/magazine/elektor-199301/32787/
[3] 1.2 GHz Multifunction Frequency Meter, part 3. Elektor Electronics February 1993:
www.elektormagazine.com/magazine/elektor-199301/32787/

112 May & June 2020 www.elektormagazine.com


The State of
Hollow State Audio
Description:
Vacuum tube (or valve, depending
on which side of the pond you live
on) technology spawned the Age of
Electronics in the early 20th century.
And today, hollow-state equipment
remains popular among high-end audio
aficionados.

In The State of Hollow State Audio,


Richard A. Honeycutt covers the history
of hollow-state audio and then dives
deep into the technical details, including
hollow-state amplifiers, vacuum tube
characteristics, and the differences in
amp sound.

You’ll learn: how hollow-state circuits


work; how to design hollow-state audio
circuits; how to find information on
vacuum tubes; how to select tubes; how

O W6 to troubleshoot hollow-state equipment;


and more

N 31,4

lektor
rs
€ fo
r mem
be

Ready for a deep dive into hollow-state


audio? Order The State of Hollow State
Audio and get started.

Read more on:


www.elektor.com/the-state-of-hollow-state-audio
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 $60.00 / £45.00
/ €50.00 each, which should encourage all Elektor readers to participate.

Participate!
Ultimately May 31, 2020, 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 2/2020 (March & April) is: 749DF.
The book vouchers have been awarded to: Etienne Guyot (France); Ria Van Broeck (Belgium);
Peter Tabatt (Germany) ; Tomas Bakke (Norway); Jose A. Gordo (Spain).
Congratulations everyone!

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

114 May & June 2020 www.elektormagazine.com


PROTEUS
DESIGN SUITE
High Speed Design Features
• Differential Pair Routing • Automatic Phase Matching
• Length Matching / Net Tuning • Use for USB, Ethernet, DDR3 etc.

Performance without the price premium.


Find out more and
configure your package on our
website or call the team on (+44)1756 753440
Win up to a
€75,000
marketing package from
Elektor and exposure at
the electronica
trade fair
COMPETE TO

LAUNCH
YOUR STARTUP AT
ELECTRONICA
2020
Is your electronics-related startup ready
to disrupt? It is time to introduce your
company’s solution to the global market!

ENTER NOW! IT’S FAST AND SIMPLE


Visit elektormagazine.com/fastforward to read the
Rules, Terms, and Conditions and to start an application.
Good luck!

FINALIST BENEFITS
First Prize = €75,000 marketing package from Elektor,
plus a booth at electronica 2022.
Second Prize = €50,000 marketing package from Elektor.
Third Prize = €25,000 marketing package from Elektor.
Get exclusive, specially priced (only €1,905!) booth
space (5 m²) at electronica 2020.
Get great exposure before, during, and after
electronica 2020. (10.-13.11.2020)

>Sign up
here
electronica Fast Forward is brought to you by
elektormagazine.com/fastforward

You might also like