88% found this document useful (8 votes)
1K views116 pages

Elektor 05-06 2022

Uploaded by

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

Elektor 05-06 2022

Uploaded by

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

£9.95 | €10.95 | $12.

95

513 MAY & JUNE 2022


ELEKTORMAGAZINE.COM
S

*
1

*
IN
CE 196

ESP32-C3
I oT Project
A Wi-Fi Button
and Relay
p. 6

FOCUS ON

Internet
of Things
p. 54 The Challenges in Bringing
IoT Solutions to Market
Worries Around Security, Scalability,
and Competition

p. 12
IoT Cloud à la Arduino p. 74
Dragino LPS8 Indoor
Convenient Solution for Gateway
Application Developers Speedy LoRaWAN Gateway Setup

DIY CO2 Guard Dual Geiger-Müller Tube Off-Grid Solar Systems


Air Quality Monitoring p. 24 Arduino Shield A High- p. 18 Design Considerations for DIYers p. 104
Made Simple Sensitivity Radiation Sensor
Join the
Elektor C mmunity
Take out a G O LD
membership
membership!

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

Also available Access to Elektor’s web archive


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

www.elektor.com/member
colophon editorial

Elektor Magazine,
English edition
Jens Nickel
Edition 3/2022 International Editor-in-Chief, Elektor Magazine
Volume 48, No. 513
May & June 2022

Learning From Mistakes


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

www.elektor.com
www.elektormagazine.com Writing an editorial means always being a few weeks ahead of your publication date. By the
time you read these lines, I very much hope you have already seen the first signs of peace in
Ukraine. And perhaps the discussions about COVID-19 measures and high incidence rates
Elektor Magazine, English edition
is published 8 times a year by
will have died down.
Elektor International Media What does the news (much of it bad) from around the world have to do with electronics? In
the last few months, we have all had to realize that our world is highly interconnected and
Head Office:
Elektor International Media b.v. globalized. Prior to the recent geopolitical issues and the COVID-19 crisis, things seemed to
PO Box 11 be going well for a few years in row! Even large corporations like the international carmakers
6114 JG Susteren had become so accustomed to the comfortable situation that few had a Plan B in the drawer
The Netherlands just in case a global catastrophe emerged.
Phone: (+31) 46 4389444
Once the current crises have been overcome, many companies will certainly not make the
Memberships: same mistakes again. Increased product availability and shorter transport routes — such
E-mail: [email protected]
things will take on a higher priority than simply securing the lowest price. This will also be
www.elektor.com/memberships
good for the electronics industry.
Advertising & Sponsoring: In many areas of electronics, the steady upswing has weakened, but things are still moving forward
Raoul Morreau
— for example, in the Internet of Things, which is the main topic for this issue. My colleague
Phone: +31 (0)6 4403 9907
E-mail: [email protected] Robert van der Zwan has put together some interesting infographics about this on page 60. Of
course, we have a variety of background articles and interesting projects for you as well!
www.elektor.com/advertising We’ll stay tuned.
Advertising rates and terms available on request.

Farewell, Not Forgetting


Copyright Notice The fact that our long-time employee Ralf Schmiedel passed
The circuits described in this magazine are for away in March 2022 was a shock for me and my colleagues.
domestic and educational use only. All draw- Ralf had been in charge of Elektor’s reader service since
ings, photographs, printed circuit board layouts,
programmed integrated circuits, disks, CD-
2014. With great patience and many ideas of his own, the
ROMs, DVDs, software carriers, and article texts engineer took care of a wide variety of concerns from readers
published in our books and magazines (other and authors, compiled corrections of projects, and helped
than third-party advertisements) are copyright
our editorial team with other tasks such as the annual DVDs.
Elektor International Media b.v. and may not be
reproduced or transmitted in any form or by any Many thank-you emails from readers showed how valuable his
means, including photocopying, scanning and support was. Ralf, we will all remember you fondly!
recording, in whole or in part without prior writ-
ten permission from the Publisher. Such written
permission must also be obtained before any
part of this publication is stored in a retrieval
system of any nature. Patent protection may
exist in respect of circuits, devices, components
The Team
etc. described in this magazine. The Publisher
International Editor-in-Chief: Jens Nickel
does not accept responsibility for failing to
identify such patent(s) or other protection. The Content Director: C. J. Abate
Publisher disclaims any responsibility for the International Editorial Staff: Eric Bogers, Jan Buiting, Stuart Cording, Rolf Gerstendorf,
safe and proper function of reader-assembled Dr Thomas Scherer, Clemens Valens
projects based upon or from schematics,
Laboratory Staff: Mathias Claussen, Ton Giesberts, Luc Lemmens, Clemens Valens
descriptions or information published in or in
Graphic Design & Prepress: Giel Dols, Harmen Heida
relation with Elektor magazine.
Publisher: Erik Jansen

© Elektor International Media b.v. 2022


Printed in the Netherlands Elektor is a member of FIPP, an organization that has “grown over almost 100 years to
include media owners and content creators from across the world.”

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


“represents the common interests of 500 German Consumer and B2B publishers.”

lektor May & June 2022 3


THIS EDITION
Volume 48, No. 513
May & June 2022

Your First Steps with an


ESP32-C3 and the IoT
A Wi-Fi Button and Relay

Regulars FOCUS
68 Narrowband Internet of Things
Standards, Coverage, Agreements, and Modules
3 Colophon
FOCUS

36 Starting Out in Electronics 74 Dragino LPS8 Indoor Gateway


Welcome to the Diode Speedy LoRaWAN Gateway Setup

40 Developer’s Zone 86 Circuit Simulation with TINA Design Suite & TINACloud
Tips & Tricks for Testing Components Sample Chapter: Sinusoidal Oscillators

68 Peculiar Parts 92 The WinUI Graphics Framework for Windows Apps


Traveling-Wave Tubes A Small Demo Application

82 Err-lectronics 100 GUIs with Python


Corrections, Updates and Readers’ Letters Worst GUI of the World

90 From Life’s Experience 104 Off-Grid Solar Systems


Assembly Line Work Electrical Energy Independent of the Mains Grid

111 Ethics

Industry
The 10-Year Smartphone
114 Hexadoku
The Original Elektorized Sudoku
FOCUS
54 The Challenges in Bringing IoT Solutions to Market

Features Worries Around Security, Scalability, and Competition

FOCUS
60 Infographics
FOCUS
Facts and Figures About the Internet of Things
12 IoT Cloud a la Arduino
Convenient Solution for Application Developers
32 MonkMakes Air Quality Kit for Raspberry Pi Dual Geiger-Müller Tube
Measures Temperature and eCO2
Arduino Shield
FOCUS A High-Sensitivity
Radiation Sensor
18
4 May & June 2022 www.elektormagazine.com
Light Switch DeLux
A Solution for High-Precision Light-
Controlled Switching
50

Tips & Tricks


40
for Testing Components
No Expensive Equipment Required

62 Preferably Wired After All


Tips for Developing a 1 Gbit/s Interface in an
Industrial Environment
Next Edition
Elektor Magazine Edition 7-8/2022 (July & August 2022)
66 Bringing Real-Time Object Detection to MCUs
As usual, we’ll have an exciting mix of projects, circuits, fundamentals
with Edge Impulse FOMO
and tips and tricks for electronics engineers and makers. We will
focus on Test & Measurement.

Projects From the contents:


> Autonomous Inductance Meter
FOCUS
> CO2 Meter with Sigfox
6 Your First Steps with an ESP32-C3 and the IoT > Design Tools for Analog Filters
A Wi-Fi Button and Relay > Smart Plugs: A Look Inside and Hacked
> Simple Analog ESR Meter
18 Dual Geiger-Müller Tube Arduino Shield > Get Started With Your Oscilloscope
A High-Sensitivity, Very Low-Power Radiation Sensor > Raspberry Pi Pico Makes an MSF-SDR
FOCUS
> AC Grid Frequency Meter
24 CO2 Guard And much more!
A DIY Approach to Monitoring Air Quality
46 Reducing the Power Consumption of Your Mole Repeller
An ATtiny13 Replaces a 555 Elektor Magazine edition 7-8/2022 covering July & August 2022
will be published around July 7, 2022. Arrival of printed copies with
50 Light Switch DeLux Elektor Gold Members is subject to transport. Contents and article
A Solution for High-Precision Light-Controlled Switching titles subject to change.
77 Explore ATtiny Microcontrollers Using C and Assembly
Language
Sample Chapter: ATtiny I/O Ports

FOCUS
83 LoRa GPS Tracker Update
Receive and Show Location Using a Raspberry Pi FOCUS ON

Internet
of Things
lektor May & June 2022 5
training

Your First Steps with an


ESP32-C3 and the IoT
A Wi-Fi Button and Relay

By Mathias Claußen (Elektor)

The IoT is not a closed book of hidden secrets. Powerful controllers like the new ESP32-C3
and newbie-friendly development environments like the Arduino IDE make developing
small projects a piece of cake.

When we speak of the Internet of Things (IoT), we acknowledge that Select the Components
more and more things in our daily lives are becoming connected to As with all projects, the right components must first be selected.
the Internet. It starts with lights, heaters and sensors in the home This is where the ESP-C3-12F kit (Figure 1), which is available in the
and continues with cars, traffic lights, shipping containers and much Elektor Store, comes into play. This board features a Wi-Fi-enabled
more. Small network-capable components are installed in each of the ESP32-C3 microcontroller from Espressif. The ESP32-C3 is a replace-
connected things, which enable exchange of information. ment for the proven ESP8266. In addition to a modern CPU core, the
  chip offers a good mix of integrated peripherals that are both begin-
The best way to get to know how to connect your own applications ner-friendly and powerful. (Refer to our review about the ESP32-C3
to the IoT is to start out with a simple practical example. In this article [1].) An overview of the integrated hardware blocks are depicted in
we create a link between a Wi-Fi enabled push button and a Wi-Fi Figure 2. In addition to the ESP32-C3, a RGB LED and a USB serial
enabled relay; the relay can be activated remotely by the button and converter are also integrated on the board. We will need two ESP-C3-
reports its status back to the push button. 12F kits for our project.

6 May & June 2022 www.elektormagazine.com


Figure 1: The ESP32-C3-12F Kit. Figure 2: Functional blocks of the ESP32-C3
(Source: ESP32-C3 datasheet).

 
In addition to the ESP-C3-12F kits, a sensor and an actuator are also Pi Zero 2 W bundle (box). For our purposes, it doesn’t however need
required. That’s where the Elektor 37-in-1 sensor kit comes in handy, to be a Raspberry Pi. Any PC running a Linux distribution such as
this kit includes 35 sensors (the original version had 37, but two of them Ubuntu [3] will also prove perfectly adequate.
contained mercury and have since been omitted on safety grounds). An  
overview of the sensors of the kit (Figure 3) can be found in Figure 4 Before we get into the project, let’s take a closer look at how the control
and the information document [2]. First of all, we will take the Joystick and exchange of data takes place in this setup.
module and use its push button feature to provide control input to the
system. The relay module can now connected to the other microcon- MQTT
troller board and acts as the actuator in the system. A few (female/ Any IoT device, whether it’s a sensor or actuator, needs to transfer data.
female) flying leads are required to connect the modules. These are For this purpose, we can either go the long way around by developing
included in the Pimoroni “Mini Breadboards & Jumpers” maker kit. our own proprietary communication protocol or we can use standard,
(See the Related Products box.) established protocols. One such system which has become widespread
  is MQTT. Originally, it was an acronym for “Message Queuing Telemetry
We also need a computer, such as a Raspberry Pi, which will act as Transport,” but as the system developed, the title no longer accurately
a local server for the IoT devices to exchange their data. An original described its function. In 2013, it was officially decided that MQTT
Raspberry Pi version 1 would in fact do the job, but we recommend would be a label [4].
at least a Raspberry Pi 2 for this application. On-board Wi-Fi was not  
included until Raspberry Pi model 3B, so to use earlier versions, a The MQTT protocol takes care of the exchange of messages using a
simple Wi-Fi dongle or Ethernet cable will also be required. If you need broker (server) without specifying what the messages look like. You
to buy a small but powerful Raspberry Pi, take a look at the Raspberry can compare this to sending a letter: the logistics and the format of

Figure 3: The Elektor 37-in-1 sensor kit. Figure 4: A whole bunch of sensors and actuators are included.

lektor May & June 2022 7


connection with MQTT, but also in many other areas. JavaScript, the
programming language from which JSON is derived, is one of the
core technologies on which the World Wide Web is based today. A
good introduction to JSON with practical examples can be found on
the Mozilla [6] site.

Setting Up the IoT Environment: The MQTT Broker


As with all projects, proper preparation helps avoid unexpected
surprises later. To handle MQTT messages, we require a broker device
that can either exist on the Internet or we can install one locally on our
network. A local broker means we won’t need to rely on cloud services
for IoT functionality that for our purposes will only be used to transfer
messages between locally connected devices. The broker can be built
using a “retired” PC or Raspberry Pi, for example. Using Node-RED,
we get a complete toolbox for developing network applications that
is not just limited to processing MQTT messages. Node-RED [7] has
already been used frequently at Elektor to process MQTT data and
can be installed quickly on a Raspberry Pi [8] or a PC [9] thanks to
the detailed instructions.

The Arduino IDE


Figure 5: Configuration of the ESP32-C3 in the Arduino IDE. The Arduino IDE is used here as the development environment.
The IDE’s editor is not the best in its class, but currently offers the
most stable support for the ESP32-C3. The Arduino IDE [10] can be
downloaded and installed free of charge from the Arduino homepage.
the envelope are specified by the postal company, but the message The Arduino ESP32 support (as described in the Espressif documen-
in the envelope and the language in which it is written is entirely up tation [11]) must now be installed. The settings for the board are made
to the user. as shown in Figure 5.
   
Which “language” should we choose to send our messages? Again, In addition to the Arduino ESP32 support, a few libraries will also be
there are several options. One popular choice (not only used for MQTT) required for our first steps. In our example for the ESP32-C3 to be able
is Java Script Object Notation (JSON). to send data via MQTT/JSON, we will need to install Nick O’Leary’s
PubSubClient and Benoit Blanchon’s ArduinoJson libraries. These can
JSON be installed using the Arduino IDE Library Manager (Figures 6 and 7).
JSON is a lightweight data interchange format for message transfer
that is easily generated and interpreted even by small microcontrol- Assembling the Hardware
lers. In addition, JSON text is not only easy to understand for humans, The two ESP32-C3 based modules are assembled according to the
but also easy to write. An overview of the JSON specification can be circuit diagrams in Figure 8 and Figure 9. The joystick and relay
found on the JSON standard website [5]. JSON is not only used in modules require just three wires connected to the respective ESP32-C3

Figure 6: PubSubClient in the


Arduino Library Manager.

Figure 7: ArduinoJson in the


Arduino Library Manager.

8 May & June 2022 www.elektormagazine.com


1 30 1 30
ADC IO18 ADC IO18
2 29 MOD2 2 29
IO0 IO19 IO0 IO19
3 28 3 28
IO1 IO9 SW IO1 IO9
4 27 4 27
IO2 IO10 VRy IO2 IO10
5 26 5 26
IO3 IO8 VRx IO3 IO8
6 25 6 25
IO4 3V3 VCC IO4 3V3
7 24 7 24
IO5 GND GND IO5 GND
8 23 8 23
NC NC NC NC
9 22 9 22
NC IO6 Joystick MOD2 NC IO6
10 21 10 21
GND IO7 GND IO7
11 20 NO Relais 11 20
3V3 MOD1 NC 3V3 MOD1 NC
12 19 COM VCC 12 19
EN RX EN RX
13 ESP32-C3F-Kit 18 NC GND 13 ESP32-C3F-Kit 18
NC TX NC TX
14 17 14 17
GND GND GND GND
15 16 Relais 15 16
5V 3V3 5V 3V3

USB USB
220017-011 220017-008

Figure 8: Circuit diagram of the ESP32-C3 and Joystick. Figure 9: Circuit diagram of the ESP32-C3 and Relay.

 
board. Note the relay board is powered from the 5 V supply pin. These three #defines at the beginning of the Arduino sketch must
Figure 10 shows all the modules and controllers connected together. be adjusted for your own network. The SSID and PASSWORD of your
network need to be entered in the appropriate position between the
Software Setup quotation marks. The IP address of the Node-RED computer in its own
The source code for this project is also available on GitHub [12]. The network is specified for the MQTT server. Once both sketches (for the
sketches for the two ESP32-C3 controllers can be downloaded from relay and for the button) have been edited they can be uploaded to the
there. It will be necessary to enter some information about your local respective ESP32-C3. Both ESP32s can then be powered up and the
network to these files before we can upload them to the ESP32s. large LED on each board should start flashing white. This indicates
Everything must be set appropriately so that the two controllers can that the ESP32-C3 is attempting to connect to the Wi-Fi network.
exchange data with the local MQTT broker. For this purpose, #define The LED should then light continuously when a board successfully
directives are present at the beginning of the two Arduino sketches: connects. The LED colour will depend on the board’s function: the
  board with the relay connected will light up white. The board with the
#define WIFI_SSID "changeme" pushbutton connected will light up red (relay off) or green (relay on)
#define WIFI_PASS "changeme" — i.e., according to the relay status.
#define MQTT_SERVER "test.mosquitto.org"  

Figure 10: The complete


hardware hook up.

lektor May & June 2022 9


Figure 11: Data transfer to the Broker and back. Figure 12: Feedback from the Relay.

This now shows that both ESP32-C3s are operating successfully. interested in a certain topic will receive the messages sent under this
Pressing the button will change the state of the relay and the colour topic. The sender, on the other hand, does not have to worry about
of the LED will change from red to green or vice versa. The button distribution. It only sends (“publishes”) its messages to the broker.
of one ESP32-C3 can thus successfully control the relay of the other  
ESP32-C3, and it also receives feedback on the status of the relay. The ESP32-C3 with the relay subscribes to the BUTTON topic in its
Time to celebrate. Your first IoT application is running! But how exactly code using client.subscribe(MQTT_TOPIC_IN); , where MQTT_
does the data exchange work? TOPIC_IN is “BUTTON” here. Every time a message is triggered by the
button, it goes to the MQTT broker. It is then delivered to the ESP32-
To the Relay and Back Again C3 with the relay, causing the relay to toggle.
First, let’s look at the path a button press takes to the relay. Figure 11  
shows how the message is packed layer by layer and then sent to When the relay changes it state, its controller sends a message to the
the broker via Wi-Fi. In the source code, this is done using client. MQTT broker under the topic “RELAIS” (RELAY), in which the current
publish(MQTT_TOPIC_OUT, (const uint8_t*)buffer, n, true);. state (whether on or off) is included. The ESP32-C3 with button, in turn,
  has subscribed to the “RELAIS” topic at the MQTT broker and thereby
Why is this function called publish and not simply send? This is due receives the message with the new status, as shown in Figure 12. This
to the way the data is later distributed in MQTT. On an MQTT broker, causes the LED colour to be set to red or green.
messages are distributed based on a topic; in this case, the topic  
(MQTT_TOPIC_OUT) “BUTTON”. When connecting to the MQTT broker, The nice thing about this structure is that a second button and control-
the client (i.e., the ESP32-C3 of our relay) can indicate which topic is ler can also be integrated into the network to send messages under
of interest (i.e., to “subscribe” to this news channel). the topic “BUTTON” — just like the first button. The ESP32-C3 with
  the relay will then respond to the control data from either button and
Each participant who has informed the MQTT broker that they are carry out the appropriate switching operation. If you’re interested in

10 May & June 2022 www.elektormagazine.com


experimenting further with MQTT, then take a look at Elektor’s other
projects that use MQTT to send data. Examples are the weather station
[13] and the monster LED clock with an external temperature sensor
[14]. For more about MQTT and how you can use it to send data to
cloud platforms, for example, refer to the series, “My Journey into The
Cloud” [15].
RELATED PRODUCTS
An Ideal Platform for the IoT
IoT does not need to be complicated. As we have shown here, the
technology is quite mature, and you can develop IoT devices quickly > ESP-C3-12F-Kit Development Board with 4 MB Flash
using simple tools and the proper components. Applications can of (SKU 19855)
www.elektor.com/19855  
course be more complex than just a simple push button and relay. From
domestic heating control to the front doorbell, there are many practi- > Elektor 37-in-1 Sensor kit (SKU 16843)
cal applications that can benefit from IoT connectivity. The ESP32-C3 www.elektor.com/16843  
is a powerful and inexpensive board that makes an ideal platform to
develop your own ideas! > Raspberry Pi Zero 2 W Bundle (SKU 19952)
www.elektor.com/19952  
220017-01

> Pimoroni Maker Essentials – Mini-Breadboards &


Jumper cables (SKU 18430)
Contributors www.elektor.com/18430
Idea and Text: Mathias Claußen
Editor: Jens Nickel
Translator: Martin Cooke
Layout: Giel Dols

Questions or Comments?
Do you have any technical questions or comments about this
article? Email the author at [email protected] or
contact the Elektor team at [email protected].

WEB LINKS
[1] M. Claußen, “Getting Started with the ESP32-C3 RISC-V MCU,” Elektor 1-2/2022: www.elektormagazine.com/210466-01
[2] Elektor 37-in-1 Sensor-Kit Documentation: www.elektor.com/amfile/file/download/file/1170/product/6171/
[3] Ubuntu Linux Distribution: https://ubuntu.com/
[4] OASIS MQTT TC Minutes from 25.04.2013:
www.oasis-open.org/committees/download.php/49028/OASIS_MQTT_TC_minutes_25042013.pdf
[5] JSON.org: www.json.org/json-de.html
[6] Mozilla Web Docs: Working with JSON: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
[7] Node-RED: https://nodered.org/
[8] Node-RED Installation on the Raspberry Pi: https://nodered.org/docs/getting-started/raspberrypi
[9] Node-RED Installation on a PC: https://nodered.org/docs/getting-started/local
[10] Arduino IDE download: www.arduino.cc/en/software
[11] Espressif Arduino-ESP32 Installation instructions: https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html
[12] Elektor GitHub Repository: https://github.com/ElektorLabs/220017-ESP32-C3-and-IoT_First-steps
[13] R. Aarts, “ESP32 Weather Station,” Elektor 1-2/2019: www.elektormagazine.com/magazine/elektor-70/42351
[14] M. Claußen, “A Monster LED Clock with Wi-Fi and Temperature Display,” Elektor 5-6/2019:
www.elektormagazine.com/magazine/elektor-96/42659
[15] J. Nickel, “My Journey into the Cloud,” Elektormagazine.com:
www.elektormagazine.com/search?query=My+journey+into+the+cloud

lektor May & June 2022 11


background

IoT Cloud a la Arduino

Source: https://dronebotworkshop.com

By Tam Hanna (Slovakia)

The Arduino IoT Cloud offers IoT application platforms such as Amazon AWS IoT Core, Microsoft IoT Hub, or
developers a convenient solution for Yandex IoT Core. If you have large numbers of devices and data to
manage, these more established IoT cloud services are the way to go.
implementing a cloud back end without  
having to struggle with MQTT. Curious? Let’s At the introduction of the latest incarnation of The Arduino IoT
take a look. cloud, Massimo Banzi, CTO at Arduino, expressed his ambitions for
the platform saying that: “Arduino now offers a complete platform
Lots of microcontroller applications nowadays involve an Internet with the MKR family; providing a streamline way to create local IoT
of Things (IoT) application where information is disseminated via nodes and edge devices. These use a range of connectivity options
IoT cloud services and an MQTT broker. Creating this type of appli- and compatibility with third-party hardware, gateway and cloud
cation using a local development environment like the traditional systems. The Arduino IoT Cloud allows users to manage, configure
Arduino IDE can sometimes be awkward. The Arduino Cloud and connect, not only Arduino hardware but also the vast majority
shifts the IDE up into the cloud so that your browser becomes a of Linux-based devices — truly democratising IoT development.”
window into the IDE. We tried it out by sending a variable value  
to the cloud to make an LED flash on the bench. Then we tried Its support of the MKR IoT-targeted range of Arduino boards and
to break it. some other popular third-party boards is a welcome addition and
  would make many IoT system developers give this accessible devel-
The basis of all IoT devices is of course the Thing. In the Arduino opment platform a second look.
IoT Cloud development environment, the Thing is a virtual object
that exists in the cloud. In the real world, it is as an object such as Setting Up the Hardware
a server, a controller board, or a similarly “intelligent” device [1]. Only the most basic plan of the four possible versions of the Arduino
Here your Thing is built in the cloud using an online editor to write Cloud is free to use. You can check out the various plans and their
a Sketch describing how it should behave and respond by using a features in Figure 1 and decide which package best meets your
whole range of Variables. needs. Of interest to the maker community generally is Arduino
Cloud’s support of third-party boards, such as the popular ESP8266
Who Will Use the Arduino IoT Cloud? and ESP32 family of devices (Table 1), and the list of compati-
Before we begin, it’s important to acknowledge that the Arduino ble platforms [2]. Driver libraries also allow various Linux-based
IoT Cloud is not an alternative for other dedicated cloud computing systems to upload and download information to the Arduino cloud.

12 May & June 2022 www.elektormagazine.com


Figure 1: Which plan is best for you? (Plan pricing as of 1/20/2022.)

 
An Arduino Nano RP2040 Connect module is used here as the target
board to test the Arduino Cloud functions. This board is based on Table 1: Boards supported by the Arduino Cloud
the RP2040 microcontroller from the Raspberry Pi Foundation
and includes a u-blox Wi-Fi module. Before setting up the Arduino WLAN
cloud, the board is connected to a computer via a USB cable. > MKR 1000 WiFi
  > MKR WiFi 1010
First, we need to visit the website [3] and apply for a new Arduino > Nano RP2040 Connect
account. For our purposes, we will stick to the basic free plan which > Nano 33 IoT
is explicitly aimed at newcomers to the system. First, we click on > Portenta H7
the Create Thing button to create a new thing. LoRaWAN
  > MKR WAN 1300
The overview in Figure 2 now shows the configuration of the three > MKR WAN 1310
basic components of the development environment. I have removed GSM/NB-IoT
a previous Arduino account and all configuration parameters so that > MKR GSM 1400
I start with a fresh device setup. The following steps are performed > MKR NB 1500
on a machine running Windows 10, but the process is identical on ESP32/ESP8266
the Ubuntu Linux environment and I have found that hardware > wide range of third-party boards
detection usually works better under Unix.
 
Now we can click on the shortcut icon in the Device section and
choose to Set Up an Arduino Device. A few seconds after clicking
this option, the back end will point out that the component called
Arduino Create Agent is missing. Click the Download button to
download the software and install it in the normal way.
 
Note that Create Agent is browser-specific: if you install under
Chrome, you will need to reinstall. Any firewall warnings that pop
up should be acknowledged. Make sure that you allow access to

lektor May & June 2022 13


Figure 3: This Arduino is connected to the Cloud.

Figure 2: The IoT Cloud leads the developer step by step through to the goal.

private and public networks alike. As a result, the Arduino Create code and sends it to the connected RP2040 using the Arduino Cloud
Agent is now resident in your taskbar — in some cases it may need Agent. If the compiled code is delivered successfully, the message
to be called up again from the start menu but that now completes "Untitled_dec25a uploaded successfully on board Arduino Nano RP2040
the driver installation. Connect (/dev/ttyACM0)” is displayed.
   
In the next step, we will refresh the view until the Arduino cloud Now after the obligatory Reset, the RP2040 will start phoning
informs us that our Nano RP2040 Connect board has been recog- home using its Wi-Fi transmitter. After a while and pressing F5
nized. Next, click the Configure button to launch the configuration several times the device will appear with “Status: online” as shown
wizard — it will ask you to enter a ’friendly” name and then initial- in Figure 3.
ize the target system’s secure element with the basic communi-  
cations software. If you chose to subscribe to one of the more comprehensive Arduino
  Cloud plans, you can receive software updates directly via Wi-Fi;
Problems sometimes arise during network provisioning under but for our simple experiments using the free plan, a wired connec-
Windows. The more reliable and successful method is to do this tion is necessary.
using Linux instead. Incidentally, the Network section is not
automatically enabled by the Arduino cloud. It is only available A Closer Look
when you create one of the variables intended for data exchange. The basic editor tool of the Sketch tab is not so useful, but by clicking
  on the Open full editor button, we get a fully-fledged cloud-based
We can now click on Variables, to open a dialog and add a new IDE that allows us to edit smaller projects more comfortably. First,
variable. First we assign the name ledIntenBool and assign Boolean let’s look at the contents of the thingProperties.h file, which contains
in the data type field. Funnily enough, the Arduino cloud not only structural elements of the sketch.
supports C programming units, but also implements wrappers  
around real world variables. First, we see the following declarations that provide the elements
  required for Wi-Fi access:
If you want to limit yourself to C only, we recommend selecting the  
Basic Types option. Theoretically, we could then make settings in const char SSID[] = SECRET_SSID; // Network SSID (name)
the Variable Permission and Variable Update Policy fields, but the const char PASS[] = SECRET_PASS; // Network password
default settings will be sufficient for our purposes, which is why // (use for WPA, or use as key for WEP)
we now close the dialog. In the next step, we then create a field of  
the Integer Number type, to which we give the name ledIntenInt. The Arduino cloud takes care of entering the name and password
using the settings already entered in the Network section. The next
Preparing the Code part contains the following two variables the names of which should
After creating the variables, red dots in the Sketch tab, indicate be familiar from their declaration in the Variables section:
changes to the program structure. Now it is possible to click on the  
shortcut icon in the Network section to enter the Wi-Fi settings. My int ledIntenInt;
preference is to enter the values u​​ sing a command line tool such bool ledIntenBool;
as iwlist on a Linux machine and then copy them to the clipboard.  
  The Arduino cloud implements the variables “in the back end" as
In the next step, we switch to the Sketch tab and click on the Verify standard C variables equipped with additional properties. These
and Upload button. The Arduino Cloud then starts compiling the properties can be found, among other things, in the initProperties

14 May & June 2022 www.elektormagazine.com


Method, which takes care of setting up the primitives and struc- void onTestScheduleChange() {
tures required for cloud communication according to the follow- }
ing scheme: void onLedIntenBoolChange() {
  }
void initProperties() { void onLedIntenIntChange() {
ArduinoCloud.setThingId(THING_ID); }
ArduinoCloud.addProperty(ledIntenInt, READWRITE,  
ON_CHANGE, onLedIntenIntChange); onLedIntenBoolChange and onLedIntenIntChange are respon-
ArduinoCloud.addProperty(ledIntenBool, READWRITE, sible for the variables created remotely in the back end, while
  ON_CHANGE, onLedIntenBoolChange); onTestScheduleChange helps implement “internal” functions of
} the Arduino cloud.
   
It is interesting here that the addProperty method, takes In the next step, we can take care of this by making use of the
care of “registering” the attribute. Note the passing of the built-in “intelligent” capabilities of the Cloud. The Arduino board
onLedIntenIntChange and onLedIntenBoolChange function point- we are using here is fitted with a standard (red) LED on Pin 13 and
ers - they will play an important role later on. an RGB LED (channels LEDR, LEDG and LEDB), which can be driven
  by three PWM signals to change the overall colour output.
The application control function is described in the sketch, which  
begins with the inclusion of the header (not shown here). This is Now we can return to the setup function, and initialise the neces-
then followed by the sketch initialization, which runs according sary pins:
to the following scheme:  
  void setup() {
void setup() { . . .
  Serial.begin(9600);   ArduinoCloud.printDebugInfo();
  delay(1500);  
    pinMode(LED_BUILTIN, OUTPUT);
  initProperties();   pinMode(LEDB, OUTPUT);
  }
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);  
  setDebugMessageLevel(2); Changes triggered in the cloud activate the listener, which writes
  ArduinoCloud.printDebugInfo(); the incoming values to the hardware:
}  
void onLedIntenBoolChange() {
From the point of view of the Arduino programming environ- digitalWrite(LED_BUILTIN, ledIntenBool);
ment, the Arduino cloud is a hardware driver like any other. The }
ArduinoCloud global object exposes a set of functions that your void onLedIntenIntChange() {
code uses to communicate with the cloud driver. Of particular analogWrite(LEDB, ledIntenInt);
importance here is the call to setDebugMessageLevel, which sets }
the “verbosity” of the driver — the higher the value, the more debug
information the cloud driver outputs over the board’s serial port.
 
In the case of “complicated” drivers, the question always arises
as to how the processing power is allocated. The project skeleton
created for us by the Arduino Cloud can answer this question in
the loop method, which takes care of the allocation of computing
power according to the following scheme:
 
void loop() {
ArduinoCloud.update();
}
 
The Arduino cloud gives us the following three listener methods
Figure 4: The Arduino IoT cloud provides detailed information
by default:
about the current state of the information stored in a variable.
   

lektor May & June 2022 15


 
At this point, you can transfer the sketch to the circuit board
again. The RGB LED uses common anode connections so individ-
ual colours are controlled by outputting a 0 to turn on the corre-
sponding LED. The variables are initialised as shown in Figure 4,
so that the blue diode of the RGB LED lights up after successful
initialization.

Modifing the Variable Contents


Figure 5: Switch the dashboard to edit mode by clicking on the
pencil icon top left.
If we return to the main back end of the Arduino cloud, we can click
on the Dashboards tab, which, if this is a new account, will prompt
you to create a new dashboard. Now click the Build Dashboard
button to launch the editor, which will take a moment or two even
if you have a fast Internet connection.
 
To modify and add elements to the dashboard click on the edit
(pencil) icon on the top left of the display (Figure  5). Once this
mode is selected the blue ADD button appears which you can use
to show the drop down list of available widgets. First, we select a
Switch widget, which then appears in the editing interface shown
in Figure 6.
 
Now over to the right of the display is the Linked Variable field
with a link button. Click on it to activate a list of all Things and
Variables contained in the cloud account. Here we can choose the
Figure 6: The editing interface for controls is “modal”.
ledIntenBool variable and link it using the Link Variable button.
The state of ledIntenBool will now be controlled by the state of the
Switch. A click on the DONE button closes the editing interface and
the switch is now incorporated into the dashboard. Now we can click
on the eye icon to release the switch to activate. Toggling the switch
on and off now controls the red LED next to the microUSB socket.
 
In order to be able to set the brightness of the blue LED, we have
to switch the dashboard editor back to edit mode and add a new
control again by using Add -> Widgets. This time I chose the Slider
type. In its editing interface, we set its Value Range from 0 - 255.
The link is made by the variable letIntenInt, which represents
the RGB LED “brightness control”. Last but not least, we switch to
activation mode here and see that changes to the slider position
now affect the brightness of the blue LED.

Using the Scheduler


As I write this article, a function for setting up scheduled tasks or
web cron-jobs is a new feature: it uses a variable type called Cloud-
Schedule that you can define to be true or false at a specific time
and for a specific time period. It’s not necessary to invoke any timer
function because this variable is set or reset automatically in the
Arduino IoT Cloud, according to how you configure it. Tasks can
then be triggered by checking the state of this variable. To demon-
strate the possibilities, let’s create a new variable of type Schedule.
Figure  7 shows the desired configuration. We can now see the
new variable type in the code:
Figure 7: The Cloud Scheduler is a data type just like all the others.  
CloudSchedule tamsSchedule;

16 May & June 2022 www.elektormagazine.com


 
At this point, I could not resist another small system test to see what
happens when the RF link goes down. The “lab Wi-Fi” was turned
off and the Arduino began to act erratically by random switch-
ing the blue element of the RGB LED and also the LED on pin 13,
eventually after a few seconds it performed a complete restart.
 
At the time this article went to press, it was not really clear to me
how exactly the Arduino cloud recovers from the loss of the radio
link between the end device and server.

A Convenient Option
It’s clear that the Arduino IoT Cloud is still a work in progress and
is under constant development and improvement. It does however
have great potential and offers the IoT application developer a
convenient and low-threshold option for implementing a cloud
back end without having the need to struggle with MQTT and Co.
Figure 8: The Scheduler is configured using the Dashboard. Despite the odd hiccup I can thoroughly recommend this product!
  210550-01

 
The time parameters for this variable are configured via the Contributors
dashboard. The settings page shown in Figure  8 show the control Idea, Illustrations and Text: Tam Hanna
elements provided for this purpose. Editor: Rolf Gerstendorf
  Translation: Martin Cooke
In the following step, we need to take care of the “local” processing Layout: Harmen Heida
of the values c​​ ontained in tamsSchedule:
 
void setup() {
. . . Questions or Comments?
  Do you have any technical questions or comments about this article?
  pinMode(LED_BUILTIN, OUTPUT); Contact the author at [email protected] or the Elektor
  pinMode(LEDB, OUTPUT); team at [email protected].
  pinMode(LEDR, OUTPUT);
}
 
void loop() { WEB LINKS
  ArduinoCloud.update(); [1] Digital twin: https://en.wikipedia.org/wiki/Digital_twin
  // Your code here [2] Boards supported by the Arduino Cloud:
  if(tamsSchedule.isActive()){ https://bit.ly/3t8Vl3W
    digitalWrite(LEDR, HIGH); [3] Arduino Things: https://create.arduino.cc/iot/things
  }
  else{
    digitalWrite(LEDR, LOW);
  }
RELATED PRODUCTS
}
 
It is important here that the “writing out” of the information > Arduino MKR WiFi 1010 (SKU 19935)
supplied in tamsSchedule is the exclusive task of the developer. The www.elektor.com/19935  
cloud is just limited to periodically updating the value contained
in tamsSchedule. The continual polling procedure shown here > Arduino Nano RP2040 connect (SKU 19754)
www.elektor.com/19754  
in the loop structure may not be optimal from a resource point of
view, but it works without problem. The program can now be sent > Arduino Nano 33 IoT (SKU 19937)
to the Arduino where you can watch for the periodic red flashes www.elektor.com/19937
coming from the RGB LED.

lektor May & June 2022 17


project

Dual Geiger-Müller Tube


Arduino Shield
A High Sensitivity, Very Low-Power Radiation Sensor

tor-labs.c
ek

om
El

BEST OF
E le

kt
m
o r-la b s.c o

By Gabriele Gorla (Italy/USA)

With two tubes for increased sensitivity, this Geiger-Müller tube shield can turn your Arduino
Uno into an instrument for measuring and recording nuclear radiation. It can even be combined
with a Dragino shield for LoRa-connectivity. Collect radiation data in the “field” — and get access
to it from all over the world! 
 
Like many other hobbyists, I have always been fascinated by radio- > Geiger-Müller Tube. The tube has two terminals and is filled
activity and the sensors to detect it. Geiger-Müller tubes [1] are a with a low-pressure gas mixture. When biased with the appro-
common and relatively inexpensive way to measure radiation. My priate voltage the gas will ionize and briefly conduct electricity
“GRAD” project is a complete solution for radiation counting in an every time it is hit by radiation. Depending on the tube type it is
Arduino shield form factor. Its main features are dual tube support to possible to detect alpha, beta and gamma particles. The SBM-20
increase sensitivity and very low power consumption. used in the GRAD is sensitive to gamma and high energy beta
radiation.
Introduction to Geiger-Müller Counters > High-Voltage Power Supply. The tube must be operated in the
Every Geiger-Müller counter requires four essential functional blocks. so-called Geiger Plateau. This is a region where the pulse count is

18 May & June 2022 www.elektormagazine.com


J1
10
SCL
9
ARDUINO UNO SDA
8
AREF R12 R7
VCC 7
almost independent of the bias J3 GND

470

470
8 6
RESERVED 13

voltage. For common tubes the


7 5 R21
IOREF 12
6 4 D6 D7 470
RESET 11 J9
bias voltage is between 400 V 5
3.3V 10
3
C20 1

and 500 V. The SBM-20 optimal


4 2
5V 9 2

POWER
3 1
GND 8 220µ
point is around 400 V. 2
GND J4 6V3

> Pulse Detector. The pulses out

DIGITAL (PWM)
1 8
VIN 7
7
J2 6 R20
of the tube are very short and 1
2
A0 5
6
5
470

of variable voltage. The pulse

ANALOG IN
A1 4 R18
3 ICSP 4
A2 3 470

RESET
SPK2
detector conditions the signal

MISO
4 3

SCK
A3 2
5 2 * *
so it can be easily counted by
A4 TX 1 SPK1
6 1
A5 RX 0

the following stage.

GND
MOSI
5V
> Pulse counting. Pulses are
counted over a fixed time inter- HV VCC VCC VCC VCC HV

val to calculate a CPS (counts


per second) or CPM (counts 330k
R2 R9 C18 C19 R15 R14

330k
5M6

5M6
per minute) value. This can be
U1E U1F
C6 R11 22p 22p C7
R16
11 10 12 13
roughly converted to a dose
330k 1 1 330k

100p 100p

rate by using the parameter on * see text 1000V GM1 GM2 1000V
+ – – +
5M6 5M6
the tube datasheet. An Arduino R3 Geiger Tube 400V Geiger Tube 400V R13

board is used for pulse count-


ing and its visualization and/or HV VCC

logging. R1
330k
D1 L1

4mH7
D2 RGP02-20

Power Supply
100V

D3
There are many circuits on the
U1B
100V
3 4
D4 1
web for Geiger-Müller tube power 100V
U1C U1D Q2
supplies. Many are boost convert- * C16 * C3 * C15 * C2 D5 100V 5 6 9 8
C4 C14
14
C1 C12
1 1 U1
ers built around the 555 timer, some 4n7 4n7 4n7 4n7 R5 10n 1µ 7 220µ 100n
1000V 1000V 1000V 1000V U1A
open loop, some with feedback.
MJ13003 6V3
10M

R4 R6
Q1 1 2
2M2 1 1k
The open-loop designs were not
considered as they require tuning R8 C5
2M2

2N3904

per board and do not provide 100p

a stable voltage at high pulse 210404-013

counts. Closed-loop designs are


more suitable as they provide the
required stability. However, to keep Figure 1: Schematic diagram of the GRAD03 project [3].
overall power consumption low,
special attention should be paid to
the feedback loop (12 µA of current
@ 400 V is ~5 mW). Zener voltage, Q1 turns on and stops the oscillator. When the output
  voltage drops again Q1 will turn off releasing the oscillator. R1 and C3
To avoid the power penalty of high-voltage feedback, the most elegant further reduce the output ripple. Additional series resistors feed each
solutions use a non-isolated step-up transformer like the Analog tube separately (R2 and R3 for GM1, R13 and R14 for GM2).
Devices LT3420. It detects the voltage on the primary side.
  Counting
We implemented a simple switch mode boost converter with a very low Pulses are picked up from the high voltage side of the tube using a DC
current feedback. Our design — shown in Figure 1 — is heavily based blocking capacitor (C6 and C7). The pulse is shaped by the remaining
on the Theremino Geiger adapters [2]. We mixed the SMD, DIY and Schmitt trigger inverters (see Figure 2).
“Flintstones” versions in a fully PTH design with Zener diode feedback.  
  J1 to J4 are the standard Arduino connectors, but GRAD only uses a
The Schmitt trigger inverter U1C, R4 and C5 form an oscillator that few pins. Digital inputs D2 and D3 were chosen as they are interrupt
generates the pulses to drive the main switch Q2. U1A, U1B and U1D pins on the Arduino Uno. This allow the Arduino to count pulses in
are in parallel to increase Q2 base current. the background while it is performing other actions.
The feedback is implemented with a series of very low leakage current  
Zener diodes (D2 to D5). When the output voltage exceeds the total Arduino digital outputs D8 and D9 are connected to a pair of LEDs

lektor May & June 2022 19


critical (high-voltage!) components needed for this project, including
data on manufacturers, type numbers and even order codes.
 
Figure 4 shows the assembled PCB with SBM-20 tubes installed. Note
that component pairs SPK1/SPK2, C3/C16, and C2/C15 respectively
just provide alternative footprints on the PCB; so only SPK1 or SPK2
will be installed. The same goes for C3 or C16, and C2 or C15. J5 and
J6 on the PCB denote two add extra footprints for connecting the
Figure 2: Scope capture of ionizing radiation hitting tube and pulse shaping. negative terminals of shorter Geiger tubes.

Tube Options
The board is designed to work with 105-mm Soviet SBM-20, STS-5
and the Chinese J305 or the 90-mm J305 and M4011. Any other 400-V
to visually show when ionizing radiation hits the respective tube. Pin tube will also work with some customized tube mounting. In case of
D4 is connected to piezo speaker SPK1 to provide audible feedback. custom mounting, to minimize parasitic capacitance, it is important
  to keep the positive wire as short as possible. For tubes requiring
Finally, digital output D5 is connected to a low-pass filter formed by different voltages, the Zener diode(s) should be changed to obtain the
R20, R21 and C20 to connect a simple analog 10 mA panel meter (J9). required voltage. Any diode with 0.5 µA or less of leakage should work.

PCB Design Performance


The schematic and PCB (Figure 3) were designed in KiCad. The design The power supply consumes 325 µW (65 µA) at 5 V. In battery-oper-
files are available for download at this project’s Elektor Labs page ated devices the board can also be powered with 3.3 V. At this lower
[3] in the Project’s Elements section. The PCB’s gerber and drill files voltage, the power consumption drops to 150 µW (45 µA).
can be found there too. You can use these to order a PCB from your
preferred supplier. Last but not least, you’ll find an Excel sheet there Arduino Sample Code
with a very detailed Bill of Materials, especially documenting the more A simple Arduino sketch to drive the counter is available in the Project

COMPONENT LIST

Resistors
R1,R2,R11,R14,R16 = 330 k
R3,R9,R13,R15 = 5.6 M
R4,R8 = 2.2 M
R5 = 10 M
R6 = 1 k
R7,R12,R18,R20,R21 = 470 Ω
 
Capacitors
C1,C20 = 220 µF, 6.3 V
C2,C3 = 4700 pF, 1000 V
C4 = 10 nF, 6.3 V Figure 3: The PCB layout.
C5 = 100 pF, 50 V
C6,C7 = 100 pF, 1000 V
C12 = 100 nF, 50 V Semiconductors U1 = 74HC14
C14 = 1 µF, 6.3 V D1 =  diode 1 A, 800 V  
C15,C16 = 4700 pF, 1000 V D2,D3,D4,D5 = Zener diode 100 V 1.5 W Miscellaneous
C18,C19 = 22 pF, 50 V D6,D7 = red LED 3 mm (Marked T1 and T2 GM1,GM2 = Geiger-Müller tube, e.g. SBM-20
  on PCB) J1,J2,J3,J4 = set of Arduino Uno shield
Inductors Q1 = 2N3904 connectors
L1 = 4.7 mH Q2 = MJ13003 SPK1 = AC piezo buzzer, e.g. AC-1205G-N1LF

20 May & June 2022 www.elektormagazine.com


Elements section of the Elektor Labs
page. Every 60 seconds, the software will
output via the serial port: a comma-sep-
arated values (CSV) row with a sequen-
tial number, raw count for each tube, a
moving average of cnt1 + cnt2 and a
µSv/h dose rate based on the average count.
The following output data fragment shows
the start of a background radiation measure- Figure
ment made in Santa Clara, CA, using GRAD 4: The
with two SBM-20 tubes.
 
Seq , cnt1 , cnt2 , avg10 , µSv/h
1 , 14 , 19 , 33.0 , 0.075
2 , 10 , 17 , 32.3 , 0.073
3 , 16 , 12 , 31.8 , 0.072
4 , 16 , 24 , 32.5 , 0.074
5 , 13 , 11 , 31.6 , 0.072
 

The graph in Figure 5 shows the complete measure-


ment over a longer period of time.
 
There are a few defines at the beginning that are
configurable to match the board configuration and/or
user preferences. The first set configures the Geiger-
Müller tube parameters and the moving window
size for the reporting.
 
#define CPM2USV 220 // tube CPM to
// µSv/h conversion
// factor
#define TUBES 2     // number of tubes
// installed Figure 5: Background radiation in Santa Clara, CA.
#define WSIZE 10    // moving average
window (in
// minutes)
   
The CPM2USV parameter is the count per minute for 1 µSv/h for your All three ...PIN defines select the Arduino pin where the LED or the
specific tube. Unfortunately, there is no published “correct” number speaker are connected. The LED_BLINK_MS defines the time that the
for this parameter. For the SBM-20 radiation, enthusiasts on the LED will stay on for each count that the tube receives.
web use values that range from 130 to 220 (conversion factor of
0.0075 to 0.0045). LoRaWAN Networking
  The basic sketch requires the unit to be tethered to a computer through
The TUBES parameter, as the name states, defines the number of USB. Often it is desirable to place the sensor far from the computer,
tubes installed. Valid values are 1 and 2. Finally, the WSIZE define the where a USB connection is not available.
moving average window size for the counts. The default value of 10  
defines a 10-minute window. A Dragino LoRa shield can be stacked to enable LoRa connectivity.
  Unfortunately, the Dragino shield also uses Arduino pin D2, so there
The second set of parameters defines how the optional hardware are two options — a single-tube option and a two-tube option.
functions are connected:  
  Single-tube option: In this case, only tube GM2 can be used and pin
#define LED1_PIN     8  // pin for TUBE1 LED 10 of Schmitt trigger U1 must be disconnected to prevent interference
#define LED2_PIN     9  // pin for TUBE2 LED with the LoRa communication. The pictures in Figure 6 show the full
#define SPKR_PIN     4  // pin for speaker connection stack with a single soviet SBM-19.
#define LED_BLINK_MS 20 // duration of LED blink for  
// each count
Two-tube option: In this case, both the Dragino shield and the GRAD

lektor May & June 2022 21


Figure 6: GRAD03 board, Arduino Uno and the Dragino LoRa shield combined.

board must be modified. For the Dragino shield, R5 and J_DIO0 must be Measuring Radiation
removed. A wire should be used to connect the radio DIO0 to Arduino D7. To verify the correct function of the Geiger counter a radiation source
  is required. These can be purchased online from special suppliers.
For the GRAD board R7, R12, C20 and the two LEDs should be removed. Alternatively, specific vintage items that were built using small quanti-
R21 should be replaced with a short, and a single LED should be placed ties of radioactive materials can be purchased at a thrift store or Ebay.
at the J9 site (replace the analog meter output). Common radioactive items include: uranium glass items, thorium
  lantern mantles and selected colors of vintage fiestaware items.
A sketch that communicates to the The Things Network (TTN) and  
posts tube counts every 60 seconds is available for download. It uses Lacking any of these, another simple way is to check the decay product
the LMIC Arduino library to drive a Dragino LoRa shield and it will of Radon captured by the air filter from an air conditioner or an air purifier
connect to The Things Network using Over The Air Activation (OTAA). (Figure 8). These have a relatively short half life (in the order of tens of
A simple Node-RED flow is used to display the data (see Figure 7). minutes) so make sure you run the AC for a couple of hours and then
measure the filter immediately. If the filter is fine enough to it will emit
radiations at a rate many times higher than background in your area.

Figure 7: Node-Red flow and dashboard.

22 May & June 2022 www.elektormagazine.com


The chart below shows the count reaching almost ten
times the background and then following the exponen-
tial curve typical of radioactive decay.
210404-01

This article is based on the material presented on the


Elektor Labs page of this project [3]. There you’ll find
all the downloads for GRAD03, plus discussions and
remarks on this subject.

Figure 8: Radiation from an air conditioner filter due to radon decay.


Contributors
Design: Gabriele Gorla
Text: Gabriele Gorla, Luc Lemmens
Illustrations: Gabriele Gorla, Patrick Wielders
Editors: Jens Nickel, C. J. Abate
Layout: Harmen Heida RELATED PRODUCTS

 
> Arduino Uno SMD Rev3 (SKU 19938)
www.elektor.com/19938  
Questions or Comments?
Do you have technical questions or comments about this article? > MightyOhm Geiger Counter Kit (incl. Case) (SKU 18509)
Email the author at [email protected] or Elektor at [email protected]. www.elektor.com/18509

WEB LINKS
[1] Geiger-Müller tubes: https://en.wikipedia.org/wiki/Geiger%E2%80%93M%C3%BCller_tube
[2] Theremino Geiger adapter (pls see three last designs on this page): www.theremino.com/en/technical/schematics
[3] This project on Elektor Labs: https://bit.ly/3giMntz

Advertisement

THE NEW COOL FA


N
NO
UP TO 1200 WATT WITHOUT FAN
MAINTENANCE-FREE POWER SUPPLIES
FOR MEDICAL AND INDUSTRIAL APPLICATIONS
▪ Convection- or contact cooled
228
.0 m
mm

▪ Operating temperature: -40° to +80°C m


mm

.2

101.6
96

▪ Medical, industrial, and ITE safety certified mm


.8
50

▪ 2 MOPP insulation system, suitable for BF type applications


▪ Optional PMBus function available*
▪ Custom variants 196
.8 m
m

127.0 m
m
m

mm
.6
.0

*RACM600-L/OF, RACM1200-V
1
76

10

WE POWER YOUR PRODUCTS


r e c o m - p o w e r. c o m / m e d i c a l

lektor May & June 2022 23


project

Ele
lab • ktor
or

lab
t
Elek
TESTED

CO2 Guard

la b
Ele
kt

or
or l kt
a b • Ele

A DIY Approach to Monitoring Air Quality

By Mathias Claußen, Ton Giesberts, and


Luc Lemmens (Elektor)
Design by Florian Schäffer (Germany)

High CO2 concentrations


can cause problems in areas
of minimal ventilation. This
CO2 guard offers a solution.
The design, constructed with
through-hole components,
warns users with three LEDs
and an acoustic alarm when it
is time for fresh air. PCB Gerber
and enclosure front panel design
The Circuit
files are free to download. The heart of the schematic shown in Figure 1 is MOD2, a Wemos
D1 Mini, which is an ESP8266EX-based Wi-Fi module with 4-MB
flash program memory. It collects data from a MH-Z19C CO2 sensor
(MOD1) via a software UART, drives three LEDs to indicate CO2
levels (LED1…3), and controls buzzer BZ1, which serves as acoustic
This CO2 Guard is a DIY project for indoor air monitoring and the alarm when the CO2 level is unacceptably high. The CO2 Guard is
assessment of air quality based on the carbon dioxide concentration powered via the micro-USB connector of the Wemos module, using
(Indoor Air Quality, IAQ). The device uses a non-dispersive infrared a standard 5 VDC mains adapter. This supply voltage is routed to
(NDIR) sensor and displays the air quality in five ranges on a triple pin 9 of MOD2 via an internal diode and fuse, and to an on-board
LED scale. In addition, an alarm sounds if the CO2 concentration is 3.3 V voltage regulator. The output of this LDO is used for the internal
unacceptably high. It is possible to transfer the measured values via power supply of the Wemos module itself and is also connected to
Wi-Fi (CO2 value and temperature) to the ThingSpeak IoT analytics pin 8 of the module. This 3.3 V could be used for powering a minia-
platform and evaluate the data graphically. ture fan connected to K1, as we will discuss later. The 5 V output of
  the MOD2 is used for powering the CO2 sensor and for an additional
There are many factors that influence air quality, but the CO2 concen- LED inside switch S1 to indicate that the Wi-Fi connection is active.
tration in a room is one that is felt almost immediately. Too high This supply can also be connected to K1 (via R6) as an alternative
concentration of this gas causes fatigue, loss of concentration, or power source for the fan. Push button S1 can trigger the CO2 sensor
even nausea, not to mention the lasting negative effects if there is to start automatic calibration. 
far too much CO2 in your environment. The latter is (hopefully!) not
likely to happen in a home or office, but this CO2 Guard can give you Powering the Fan
a timely indication to ventilate a room.  In this project, the fan is not used for cooling, but for airflow past the

24 May & June www.elektormagazine.com


sensor. Although it seems obvious to power a 5 V fan at its nominal the transistor. The PCB has footprints for both 6.5 mm and 7.62 mm
voltage, if maximum airflow is not the most important design consid- pitch buzzers.
eration — as in this project — it may be a good idea to minimize the  
noise of this device by reducing the airflow via the supply voltage. The switch we used for S1 is one with an optical indicator in the form
With our CO2 Guard, there are some options in this respect. of a blue ring. No external resistor is needed for the LED inside the
  switch. The pins with + and – markings on the PCB, next to two
The 3.3 V supply rail of the Wemos module is regulated by an low pins for the switch, are the two connections for the LED. Four wires
drop out regulator (LDO) in a SOT23-5 package. The maximum output are connected to four-way pin header S1 (or soldered directly to the
current of this LDO is limited to 150 mA due to its package. A signif- PCB). Of course, you can also use a separate switch and LED, R5
icant portion of the output current is used for the ESP8266 of the then sets the current for the LED and the front panel design needs to
Wemos D1 Mini module itself. Overloading the LDO can result in be modified to accommodate this optical indicator. With the switch
instablility of the ESP8266 and therefore random crashes. To avoid prescribed in the component list, R5 is not needed and must be
overloading the 3.3 V regulator, there’s an option on the PCB of replaced with a jumper wire. 
the CO2 Guard to connect the fan to 5 V through a resistor (R6,
the footprint on the PCB is for a 1 W type) to the 5 V. This makes it PCB
possible to reduce the airflow and, more importantly, the noise even The design and Gerber files for the printed circuit board shown in
further. Be aware that fans runnung at a lower voltage as they are Figure 2 are available for download from the GitHub repository [1]
designed for tend to have problems during startup or not starting of this project. With the Gerber files, you can order the board from
at all. If the fan should be directly connected to 5 V, a jumper wire your preferred PCB manufacturer. All components are through-hole
can be used for R6 instead. and the PCB could be single sided; the top layer of the PCB is only
filled with copper to avoid the additional costs that single-layer PCBs
Other Hardware will have nowadays. So, even for inexperienced makers, soldering
The buzzer is also powered by the 5 V supply. The high output level will be not too difficult if the guidelines given here are followed. And
of the I/Os of the D1 Mini is 3.3 V, so to turn the buzzer off, the with all traces on the bottom layer of this PCB, it is relatively easy to
voltage divider R4/R7 is connected to the base of PNP transistor T1. desolder components if a mistake is made. Start with mounting the
Some buzzers are inductive and likely to produce spikes, especially lowest components first, resistors and diode, then the capacitors,
when switching off. Diode D1 prevents these spikes from harming transistor, buzzer and headers (sockets for the CO2 sensor MOD1,

+3V3 +5V
K1 R6 * C2
+3V3 0R
C3*
FAN 100n
+5V
100u
+5V 50V MOD1 FAN
VIN +3V3 0 +5V C3
Vo RX R6
R7 S1
SR TX R5
S1
AOT PWM
1k5

GN D
D1
T1 HD A
LE D

GND K

BC327 R4 MH-Z19C *see text


BZ1
4k7

C1 M OD 1
BZ1 D1 C1 R3 R2 R1 M OD 2
LE D 3 LE D 2 LE D 1

+5V
T1
BAT85 100n R4

MOD2 R5 *
1 16 R7
RST TX
0R

R1 C2
2 15 S1 S1
LED1 330R A0 RX
3 14
D0 SCL/D1 S1
R2 4 13
D5/SCK SDA/D2
LED2 330R 5 12 EL EK TOR
D6/MISO D3 A 210 043-1
6 11
R3 D7/MOSI D4 K
7 10
LED3 330R D8 GND
8 9 LED_S1
+3V3 3V3 5V +5V
WEMOS_D1_MINI
210043-001
Figure 2: PCB of the CO2 Guard.
Figure 1: Schematic of the CO2 Guard.

lektor May & June 2022 25


Figure 3: Installed fan.

optional pin headers for the switch and LEDs). To mount the D1 Mini placed correctly on the screw fixings, maybe use two screws tempo-
module (MOD2), first solder the two eight-pin male headers to the rarily, the position of the notch can be marked. It’s slightly off center.
side of the module where the USB connector and most of the other  
components are located (see Figure 3). We advise not using sockets No holes need to be made for the fan’s airflow; it is glued to the
on the PCB for MOD2, since there’s some force on the module when bottom side of the enclosure with super glue or epoxy adhesive
plugging and unplugging the USB connector. It’s best to solder the (Figure 3). To avoid resonance the fan should not touch the lid of
D1 Mini onto the PCB. Also, using sockets could limit airflow through the enclosure. The fan should blow air out of the enclosure. Before
the ventilation holes of the enclosure. mounting it, check the direction of the airflow by connecting it to
  a 3.3…5 V power supply or check if there is an arrow on the side
When the PCB is fixed with four screws to the bottom half of the of the fan’s frame depicting the flow direction. Pay close attention
enclosure and the fan glued (see below), the sensor module can be to the polarity of the wires. The wrong polarity will damage the fan.
plugged into the corresponding sockets. Never touch the top of the (Modern ones often have some circuitry inside.)
sensor, as stated in the datasheet [2]: “Please avoid the pressure of
its gilded plastic chamber from any direction, during welding, installa- Connecting the Front Panel Parts
tion, and use. Especially never touch the air intake (white dust filter).” To connect the LEDs, only four wires are needed. The ground connec-
  tion from the PCB to three LEDs on the front can be one common
The four and five pins sockets for the sensor will probably be supplied connection, simply connect three cathodes of the LEDs and use
as one 10-pin SIL socket. Cut this socket strip at the location of the one single wire.
fifth pin to get a separate four- and five-pin socket.  
Make sure no wires lie on the antenna of MOD2 when the lid of the
Preparing the Enclosure enclosure is finally placed on the bottom part. Keep them as far away
Use a copy of the front panel design as a template for the correct as possible from the Wemos module, but don’t make them longer
positions for the four holes (three LEDs and the switch), and use a than necessary. Wires to the switch can be as short as 8.5 cm and
punch tool to mark the four centers. On this project’s page on Elektor the wires to the LEDs about 12 cm. With this length of the wires, you
Labs [3], there are some tips and tricks to prevent damage to the can remove the top of the enclosure and place it on its side next
case when drilling larger holes in the plastic front panel. With this to the bottom with all wires still attached. No screws are needed to
type of enclosure, pay special attention to the long pins that are used close the enclosure; four long plastic pins of the lid slide into four
to close it; they can break if not handled properly! long mounting bosses.
   
A notch must be made in one side of the bottom half of the enclosure Of course, feel free to create your own front panel design. You can
to access the micro-USB connector of the D1 Mini module, which use a separate blue LED and switch for instance. But be aware of
serves as the power supply for the CO2 Guard. Make sure the notch the placement of the LEDs and switch; they should not be located
is big enough for the USB-plug of your power supply. Place the D1 too close to the modules.
mini module on the PCB to mark the correct place for the notch. No
need to solder the module with the accompanying male headers Getting Firmware to the Wemos
to the PCB yet. With the module placed on the PCB and the PCB The firmware for the ESP8266 on the Wemos module is written using

26 May & June www.elektormagazine.com


Figure 5: Button for the firmware upload.

Figure 4: Code loaded into PlatformIO IDE.

the Arduino Framework, so you need the sketch and a set of libraries.
For the development of the code of this CO2 Guard, PlatformIO and
Visual Studio Code are used. Libraries, project, and upload settings
are combined so that compiling the code should not be that much
of a problem.
 
To install Visual Studio Code and PlatformIO, you can follow the
guide [4] PlatformIO provides. After the installation, you need to
grab the source code from the Elektor GitHub Repository. If you
Figure 6: Small ant head shows more options.
are in doubt how to get the code, have a look at the video that our
colleague Clemens Valens [5] created. Also, if you would like to
know more about GitHub and the usage of Repositories, take a look
at the Elektor Webinar about GitHub [6]. After you have the code
and open it with the PlatformIO IDE, it should look like what you
see in Figure 4. Connect the Wemos to your computer and hit the
upload button (Figure 5). PlatformIO will download all the required
libraries, tools, board support packages and start compiling and
afterwards uploading.
 
PlatformIO now has built and flashed the firmware. As with most
ESP8266 projects, there is a second part to it. As the firmware
offers configuration through a webserver, we need also to write
the webpages to the ESP8266 in a second step. Click in Visual
Studio Code on the small ant head and a list of tasks should appear
(Figure 6). First click on Build Filesystem Image and afterwards on
Upload Filesystem Image. This will write the content for the Webserver
to the ESP8266. If you get errors like “can’t access COM port,” make
sure you don’t have a serial terminal somewhere open that will block
the port. Afterwards, firmware is ready to be configured and used.

Wi-Fi and Cloud Connectivity


If your ESP8266 on the Wemos module can’t connect to a Wi-Fi
network, it will start an access point called “CO2 Meter”. Connect to
it and open a browser pointing to http://192.168.4.1. You should see
Figure 7: Wi-Fi settings.
the WiFi Manager configuration interface (Figure 7). Hit Configure
WiFi and select your network and apply the required settings before

lektor May & June 2022 27


Figure 8: CO2 Guard web interface.

Figure 9: ThingSpeak settings.

Figure 10: New generated ThingSpeak channel. Figure 11: ThingSpeak settings.

Figure 12: Arriving data.

28 May & June www.elektormagazine.com


hitting save. The ESP8266 will now try to connect to your network. network. One of the tools that offers MQTT connectivity is Node-RED
If it can establish a connection, you can use within your network (e.g., on a Raspberry Pi). We have covered a lot on installations for
http://co2guard.local to access the web interface (Figure 8). From Node-RED in the past, and if you want a quick installation guide for
here you can start configuring the CO2 guard. your Raspberry Pi, have a look at the Node-RED website [9]. For
  MQTT within the CO2-Guard’s web interface, you can provide a server
If you like, you can connect the CO2 Guard to a web-based data and a topic where data should be published (Figure 13). The data
storage solution like ThingSpeak or an MQTT broker, like the one used itself is transferred as JSON string, having the objects “CO2Value”
in Node-RED. With the latter, you can add even more automation to and “Temp”, presenting the CO2 value in ppm and the tempera-
the sensor — for instance, sending a message to your mobile phone ture in °C. If you would like to read more about Node-RED using a
if the CO2 exceeds a certain level. To get started with ThingSpeak, a Raspberry Pi, have a look at Dogan Ibrahim’s book, Programming
short tour through the account setup is provided. with Node-RED (Elektor 2020) [10].

ThingSpeak: Create a MathWorks Account KiCad PCB Design Files


If you only want to monitor the current concentration of CO2 in the The PCB was originally designed in Altium, and the provided Gerber
room you are in, you do not need a Wi-Fi connection and certainly files are based on this proven design. The design is quite simple as you
not access to a ThingSpeak account, the LEDs (and in extreme can see from the schematics. As the schematic is not that complex
cases: the buzzer) then give a clear indication of the air quality, at (see Figure 1), it was recreated in KiCad. Besides the schematic, the
least: regarding CO2. But if you want, for example, to log the course PCB needs to be transferred, but as the project started in the last
of these measurements and analyse the data over time, or be able stable version of KiCad 5, there was no native (integrated) import
to see from a greater distance what the current concentration is, for Altium boards around. One trick is to use the provided Gerber
then connecting to ThingSpeak via Wi-Fi is an obvious choice. You files and import them into KiCad. The Gerber viewer in KiCad is able
can then also follow the temperature, which is also measured by the to generate board files you can use in the PCB layout tool. Not only
sensor module, but not displayed in any way on the CO2 Guard itself. does this give the outlines of the board but also the footprints and
  mounting holes we can use for the component placement. This is a
To create an online channel for your measurements, go to the Thing-
Speak website [7] and choose Get Started For Free. On the next
page you can create a MathWorks account (if you don’t already have
one). After this, create a new channel and enter the required data as
suggested in Figure 9. Click on Save Channel. An overview of the
channel just created is shown as in Figure 10.
 
At the tab API Keys, we need to copy the Write API Key for later use.
Keep it private and don’t show it to anyone else. Go to the CO2 Guard’s
web interface and select the ThingSpeak option on the side menu.
A page with the settings for ThingSpeak will show up. Enter the API
Key, select an upload interval and enable ThingSpeak (Figure 11).
You now switch back to the MathWorks ThingSpeak site. Under menu
Channels choose My Channels and then the tab Private View. It should
show after a short time the first measurements like in Figure 12.
 
To share your data with others, you are able to add individual users
with viewing permission, or you can make the channel public so
anyone can view your data. Individual users will get an email to the
email address you can enter in the tab Sharing. If you are using a
free (non-paid) plan for ThingSpeak, the sharing of data is limited
to only three other users. For more details about sharing data you
can consult the MathWorks help center  [8].

MQTT Connection
MQTT is a versatile way to distribute your data to other systems Figure 13: MQTT Settings.
that can store or process it. You don’t need an external service to
collect data or process it, and you can keep the data within your own

lektor May & June 2022 29


 
way that can be used to import PCBs into KiCad, but it is preferred Want to build your own? You will need to spend around €30 for the
to use the KiCad version 6 and the native Altium board import if you sensor (in Europe). The switch, Wemod D1 mini, PCB, LEDs, enclo-
have Altium files. sure, fan and shipping will add to the bill, so you will end up at around
  €60€ in parts. On the other hand, monitoring the CO2 concentration
But why should someone do this conversion? First, this allows others in your rooms has a lot of advantages. If you know the CO2 concen-
to directly work with the KiCad files and modify them if wished. Also, tration, you can ensure that there is enough fresh air.
with some PCB services it is just drag and drop for a KiCad board file 210043-01
to get your board manufactured (e.g., at Aisler) [11]. You don’t have
to export to Gerber and drill files to generate a ZIP file. However, if
your PCB service needs Gerber and drill files, you are still able to Questions or Comments?
generate them in KiCad to the specifications your service requires. Do you have technical questions or comments about this article?
  Email Elektor at [email protected].
If you would like to design your own enclosure around the PCB, the
combination of KiCad and FreeCad has proven to work very well, as
you can see from the Christmas project [12]. And printing an enclosure Contributors
may be for some more convenient than drilling holes into a preman- Original hardware design: Florian Schäffer
ufactured one. And if you have a 3D printer at home that is collecting Design and Text: Mathias Claußen, Ton Giesberts, Luc Lemmens
dust, why not use it? Also, it means one component less to order. Editors: Jens Nickel, C. J. Abate
For the 3D-printable case, as at the time of writing this article, it is Layout: Harmen Heida
currently not finished, but it is being worked on. So, in the meantime,
if you want to use an enclosure, you need to drill some holes.

Build Your Own


Building a CO2 sensor for your home or workspace is not that hard,
and as you know, many CO2 meters have been developed as both DIY
and commercial projects. With the MH-Z19 sensor used in this project,
you get decent affordable measurement source. The ESP8266 is a
well-proven Wi-Fi microcontroller that not only can be programmed
with the Arduino Framework but also offers in the current combina-
tion support for Home Assistant.

Software
For the software that was originally provided by the developer on Inside the software, the dataflow is quite simple, as you can see in
the Elektor Labs platform, there were a few areas that could use the picture. Every two seconds the sensor values are queried and
improvement. For example, hard-coded credentials for your Wi-Fi moved back to various code modules. For the local supervising
network work only if you never change the network name or the of the CO2 level, we have the limits class, which will control in the
password the device is connected to. Also having your credenti- end our three LEDs, and we have the alarm class, which will sound
als somewhere in some code files is not the safest way to store the buzzer if a certain level of CO2 is exceeded. Those classes are
them. The same is true for the ThingSpeak API Key. If you need to built in a generic way that makes it easy to change the LED arran-
change this key, it means you need to recompile the whole code gement for a different way of displaying the values. Same goes for
and upload it to the device. the buzzer. If you like to use an active one or even a sound module,
  this class is flexible enough to accomplish this.
What the Elektor lab left hardcoded (as #defines in /configure/  
configure.h) is the pin mapping, as well as the CO2 tresholds for the For the cloud connectivity, where possible, pre-built libraries have
three LEDs and the buzzer. In the file /configure/configure.h, you been used, especially for ThingSpeak. This makes the data exchange
have all hard coded settings in one place and can change them if with this service a lot simpler than on the ESP32 Weatherstation
needed. If you change any settings in this file, you must rebuild the [13] we published [14] a few years ago.
firmware and upload it to the ESP8266, of course.

30 May & June www.elektormagazine.com


COMPONENT LIST
Resistors MOD1 = MH-Z19C, version 400-5000 ppm, pins on bottom
R1,R2,R3 = 330 Ω, 0.25 W, 5 % MOD2 = Wemos D1 mini with 2x  1x8 SIL header
R4 = 4.7 kΩ, 0.25 W, 5 % S1 = switch with built-in LED (momentary on, self-reset, blue circle)
R5 = 0 Ω, place wire, see text Enclosure PP73BL, Supertronic
R6 = 0 Ω, place wire for 5 V or leave open, see text BZ1 = DC buzzer, 5 V, pitch 5 or 7.62 mm, diam. 14 mm max
R7 = 1.5 kΩ, 0.25 W, 5 % heat shrink tube, I.D 2.4 mm, 20 cm
  LED housing, for 5 mm LED (LED1..3), Black
Capacitors FAN 5 VDC, 30x30x10.5 mm
C1,C2 = 100 nF, 50 V, 10 %, X7R, lead spacing 5 mm 12-pin male SIL header  
C3 = 100 µF, 25 V, optional , not mounted, see text PCB 210043-1 v2.0
 
Semiconductors Thin stranded wire to connect LEDs and switch:
D1 = BAT85, DO-35 stranded wire, 0.25 mm2, black (2x8.5+12 cm)
T1 = BC327, PNP, TO-92 stranded wire, 0.25 mm2, red  (8.5+12 cm)
LED1 = LED red, 5 mm stranded wire, 0.25 mm2, yellow (12 cm)
LED2 = LED yellow, 5 mm stranded wire, 0.25 mm2, green (12 cm)
LED3 = LED green, 5 mm stranded wire, 0.25 mm2, blue (8.5 cm)
 
Other
MOD1 = 1x10 SIL header, female, split in 1x4 and 1x5 (see Text)

RELATED PRODUCTS

> WeMos D1 mini Pro – ESP8266 based WiFi Module (SKU 19185)
www.elektor.com/19185  

> PCB V2.1 with Components (excluding WeMos D1 and MH-Z19)


www.elektormagazine.de/aisler/co2guard  

> H. Henrik Skovgaard, IoT Home Hacks with ESP8266 (SKU 19158)


www.elektor.com/19158  

> D. Ibrahim, Programming with Node-RED (E-book) (SKU 19225)


www.elektor.com/19225

WEB LINKS
[1] Elektor GitHub Repository: https://github.com/ElektorLabs/210043-CO2-Guard
[2] Winsen MHZ-19 datasheet: www.winsen-sensor.com/d/files/infrared-gas-sensor/mh-z19b-co2-ver1_0.pdf
[3] “CO2 Guard,” Elektor-Labs.com: www.elektormagazine.de/labs/co2-guard
[4] PlatformIO install guide: https://platformio.org/install/ide?install=vscode
[5] “How to Code (Download) or Clone Something From GitHub,” Elektor TV: www.youtube.com/watch?v=X5e3xQBeqf8
[6] “GitHub Webinar: My Way Into GitHub,” Elektor TV: www.youtube.com/watch?v=j_LgvVhBdwQ
[7] MathWorks ThingSpeak: http://thingspeak.com
[8] MathWorks ThingSpeak Help: https://bit.ly/ChannelPropertiesMATLAB
[9] Node-RED installation guide: https://nodered.org/docs/getting-started/raspberrypi
[10] D. Ibrahim, Programming with Node-RED, Elektor 2020: www.elektor.com/programming-with-node-red-e-book
[11] AISLER B.V: http://aisler.net
[12] M. Claußen, “DIY Christmas Fireplace: A 3D Puzzle with PCBs, LEDs, and Raspberry Pi Pico,” ElektorMagazine.com:
www.elektormagazine.com/articles/diy-christmas-fireplace-3d-puzzle-pcbs-leds-raspberry-pi-pico
[13] “ESP32 Weatherstation,” Elektor-Labs.com: www.elektormagazine.com/labs/esp32-weather-station-180468
[14] R. Aarts, “ESP32 Weatherstation,” ElektorMag 1-2/2019: www.elektormagazine.com/magazine/elektor-70/42351

lektor May & June 2022 31


review

MonkMakes
Air Quality Kit for
Raspberry Pi
Measures Temperature and eCO2

By Luc Lemmens (Elektor) Thermometers have long been used to monitor room temperature, and
in recent years, (e)CO2 meters have become increasingly popular for
Most of us are now stuck in monitoring air quality. Too much carbon dioxide (CO2) has a negative
(private) rooms, so modules effect on concentration, and at even higher levels it is bad for your
for measuring the air quality health. This kit measures the quality of the air in a room (how stale
the air is) as well as the temperature. It is meant as an add-on for the
cheaply are gaining popularity. Raspberry Pi, but it also can be used as a stand-alone device. The board
The MonkMakes Air Quality has a buzzer and a bar of six LEDs (two green, two orange, and two
Kit measures equivalent CO2 red) that displays the air quality. Temperature and air quality readings
can be processed by a Raspberry Pi. The buzzer and LED display can
and temperature. It is especially be controlled by the host.
designed to be used with a  
Raspberry Pi 400, but it can also be The kit comes without printed documentation, but it provides a link to
the MonkMakes website where the datasheet and instructions can be
connected to other Raspberry Pi downloaded [1]. These documents contain all relevant information; they
models using the jumper wires and help the user to connect and use the board. Example applications in
an included GPIO template. Python are available for download on Github [2].

The Hardware
Besides the six indicator LEDs and the buzzer — the big square compo-
nent in the middle of the PCB in Figure 1 — the board contains a power

32 May & June 2022 www.elektormagazine.com


LED, a temperature sensor, an eCO2 sensor, a microcontroller and of
course a 40-pin connector that fits directly on the expansion connector of
a Raspberry Pi 400 (Figure 2). Perhaps needless to say: other Raspberry
Pi boards can not be connected directly, for that the jumper wires are Figure 1: The kit contains the
included. The four connections needed (two for the power supply, two board, jumper wires and a
template to locate the GPIO-
for the serial connection) are shown in the print on the MonkMakes
connector pins. (Source:
board and on the supplied template to match the corresponding pins of MonkMakes)
the GPIO connector of the Raspberry Pi, as illustrated in Figure 3. The
power LED lights up as soon as the 3.3 V supply voltage is switched
on, and so will one of the eCO2 level LEDs.
 
The temperature sensor is a Texas Instruments TMP235 [3]. Its output
voltage is proportional to the temperature. For CO2 measurement,
the MonkMakes board uses a CCS811 TVOC (Total Volatile Organic
Compounds) sensor [4]. This does not actually measure the level of
CO2, but rather the level of a group of gasses called Volatile Organic
Compounds (VOCs). When indoors, the level of these gasses rises at a
rate comparable to that of CO2, and can therefore be used to estimate
the level of CO2 (called the equivalent CO2 or eCO2). Figure 2: Air Quality Kit connected to a Raspberry
  Pi 400. (Source: MonkMakes)
The on-board ATtiny1614 microcontroller reads both sensors and controls
the LED bar display and the buzzer. Via a serial protocol, a host system
can request sensor readings or switch the LEDs and buzzer on and off.
The kit’s datasheet documents this simple protocol, so it will not be too
difficult to write your own software to support the Air Quality Kit. As
name of this kit indicates, it is designed for Raspberry Pi, but there is
no reason why you shouldn’t use it with other boards or systems with
a 3.3 V UART.
 
The firmware of the ATtiny also offers an automatic mode (switched
on by default) that shows the eCO2 level on the LED bar without any
external control; all that is needed is a 3.3 V power supply. So, even
without a host system, the Air Quality kit can be used as eCO2 monitor.
Figure 3: Don’t plug in directly,
Software use the jumper wires to connect
As mentioned earlier, MonkMakes offers downloads of some Python the kit to other Raspberry Pi
example programs to control this Air Quality Kit to test and demonstrate models! (Source: MonkMakes)
all its features. In the Getting Started section of the documentation, the
instructions clearly show how the software can be used on a Raspberry Pi
board to implement an eCO2-meter, an eCO2-meter with acoustic alarm
(Figure 4) and a data logger application. Looking at the examples, like
in Figure 5, you’ll notice that the ATtiny and the API completely relieve
you of retrieving and evaluating sensor data: one simple instruction
from the host (Raspberry Pi) will trigger the Air Quality board to echo
the current ambient temperature (in °C) or CO2 level (in ppm), respec-
tively. Similar commands are used to switch the buzzer on and off, and
to control the LEDs of the eCO2 bar display.

A Nice Design
Only some basic knowledge of the Raspberry Pi is required to get this
Air Quality kit working. What is a great advantage for some, will be less
attractive for others: knowledge of the sensors and control of buzzer and Figure 4: Raspberry Pi screen output for one of
LEDs is not required. The (source code of the) firmware of the on-board the examples. (Source: MonkMakes)

lektor May & June 2022 33


Sensor Characteristics
eCO2 minimum reading 400 ppm
eCO2 maximum reading 4095 ppm
eCO2 resolution 1 ppm
Figure 5: Python source, showing that only simple, short instructions are
eCO2 accuracy unspecified
needed to communicate with the Air Quality Kit.
Temperature minimum reading -10 °C
Temperature max reading 100 °C
Temperature accuracy +/- 2 °C
ATtiny1614 is not released (i.e., we don’t know what exactly happens inside
this microcontroller). However, the protocol to communicate with the
board is simple and well documented, and development of your own
applications — even for other target systems than Raspberry Pi boards
— will be relatively easy. The MonkMakes Air Quality Kit for Raspberry Pi
is a nicely designed, well-documented board that, together with the About CO2 Concentrations
examples, is also suitable for beginners who want to get started with The level of CO2 in the air we breathe has a direct influence on our
temperature and eCO2 measurements.  well-being. CO2 levels are of particular interest from a public health
210681-01 point of view. To put it simply, they are a measure of how much we
are breathing other people’s air. We humans breathe out CO2, and if
Questions or Comments? several people are in a poorly ventilated room, the level of CO2 will
Do you have questions or comments about his article? Email gradually increase — as well as concentration of aerosols that spread
the author at [email protected] or contact Elektor at colds, flues and Coronavirus. Another important impact of CO2 levels
[email protected]. is in cognitive function — how well you can concentrate and think.

The table below shows the levels at which CO2 can become unhealthy.
Contributors The CO2 readings are in ppm (parts per million).
Text: Luc Lemmens
Illustrations: MonkMakes, Luc Lemmens
Editors: Jens Nickel, C. J. Abate
Layout: Harmen Heida Level of CO2
250-400 Normal concentration in ambient air.
400-1000 Concentrations typical of occupied indoor
spaces with good air exchange.
RELATED PRODUCTS 1000-2000 Complaints of drowsiness and poor air.
2000-5000 Headaches, sleepiness and stagnant, stale,
> MonkMakes Air Quality Kit for Raspberry Pi (SKU 19913) stuffy air. Poor concentration, loss of attention,
www.elektor.com/19913 increased heart rate and slight nausea may
also be present.
> Raspberry Pi 400 – Raspberry Pi 4-based PC (US) +
FREE GPIO Header (SKU 19429) 5000 Workplace exposure limit in most countries.
www.elektor.com/19429 >40000 Exposure may lead to serious oxygen
deprivation resulting in permanent brain
> Raspberry Pi 4 B (1 GB RAM) (SKU 18966) damage, coma, even death
www.elektor.com/18966

WEB LINKS
[1] MonkMakes webpage with instructions: http://monkmakes.com/pi_aq
[2] Software on Github: https://github.com/monkmakes/pi_aq
[3] TMP235 datasheet: https://www.ti.com/product/TMP235
[4] CCS811 datasheet: https://www.sciosense.com/products/environmental-sensors/ccs811-gas-sensor-solution/

34 May & June 2022 www.elektormagazine.com


e-zine
Your dose of electronics

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


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

So, why wait any longer? Subscribe today at


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

What can you expect?


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

Starting Out in Electronics


Welcome to the Diode

By Eric Bogers (Elektor)

It has taken a while, but we have finally wrapped up our discussion


about the ‘passive’ components. In this instalment we begin our
discussion with a few ‘active’ components – the semiconductors, to
be precise. Now it really becomes interesting!

We commence our discussion of the active components with the If we were writing a ‘real’ textbook, we would have to fill many
diode and related components. Granted, you could argue endlessly pages with information about semiconductor materials (silicon,
about the question whether a diode is an active or a passive compo- germanium, selenium and others), doping, PN-junctions and many
nent — active components are called that because they are able to other things; but this series of articles is targetted at the begin-
amplify a signal, and a diode does not do that. But because they are ning electronics enthusiast and not at physicists or semiconduc-
semiconductors components (or, in the past, electron tubes, but tor manufacturers. The beginning electronics enthusiast is mostly
these are outside the scope of this series of articles) we put them interested in the question of what function a particular compo-
in the same heap with transistors and other active components. nent accomplishes and how they can use it in their designs — and
  much less in the question of how and why a particular component
does what it does.
 
In Figure 1 you can see a few common implementations of diodes.
At top left are two ‘ordinary’ diodes: a 1N4148 and a 1N4001. At
bottom left are three LEDs (light emitting diodes), with diameters
of 3 mm, 5 mm and 10 mm. On the right you can spy a set of four
bridge rectifiers — these are combinations of four diodes in a single
housing. These are used in large numbers in (mains) power supplies.
The example at bottom right has a metal housing and is intended
to be bolted to a heatsink; this rectifier can handle a current of no
less than 25 A.

Figure 1: Several diodes and bridge rectifiers.

36 May & June 2022 www.elektormagazine.com


I[mA]
Diode I[mA]
10 Ω
12 12
11 11 50 Ω
10 10
9 9
Light Emitting Diode (LED) 8 8
7 7 100 Ω
6 6
5 5
4 4
3 3
2 2 500 Ω
Zener diode 1 1

0,1 0,2 0,3 0,4 0,5 0,6 0,7 U[V] 0,1 0,2 0,3 0,4 0,5 0,6 0,7 U[V]

Figure 2: Schematic symbols for a few Figure 3: The V/I-characteristic of a diode. Figure 4: V/I-characteristics of four
common diodes. resistors.

The Diode maximum voltage in the reverse (blocking) direction (where


A diode can be considered as a kind of valve for electric current: the cathode voltage is more positive than the anode). Often the
the component conducts in one direction but not in the other. maximum power handling (the maximum dissipation) of a diode
In Figure 2 you can see the schematic symbols for a few diodes; is also mentioned.
from top to bottom: an ordinary diode, a light-emitting diode  
(LED) and below that are two versions of the symbol for a Zener The maximum current capability of the 1N4148 (a ‘typical’ small-sig-
diode (in the bottom symbol the ‘Z’ for Zener can be recognised). nal diode) that is used as the example here, amounts to 100 mA,
The diode symbol resembles an arrow that points in the direc- while the maximum dissipation is 500 mW.
tion in which the current can flow. The connection on the left in  
Figure 2 is called the anode and the one on the right (the bar) is On the other hand, a diode is not able to block arbitrarily
called the cathode. high voltages either. When the maximum blocking voltage is
  exceeded, the diode also starts to conduct in the reverse direc-
A (silicon) diode starts to conduct once the voltage at the anode is about tion. If the current is not severely limited in this case, the diode
0.6 V more positive than at the cathode — somewhat comparable to a will overheat and the silicon semiconductor crystal will melt —
mechanical valve where a certain pressure difference is required before after which the diode will forever conduct in both directions…
the valve opens. And before you ask where this 0.6 V comes from: this This higher voltage also results in a much higher dissipation,
is determined by the semiconductor material, in this case silicon. In a so that the diode will be destroyed by a comparatively small
germanium diode this minimum voltage amounts to about 0.3 V. A current in the reverse direction.
physicist can undoubtedly explain in fine detail why exactly it is that
way, but here it is of no importance to us. We only remember these Regulation of Voltages
two voltages: 0.6 V for silicon and 0.3 V for germanium. Using ordinary diodes a reasonably stable voltage can be obtained
  in a very simple way (see Figure 5). First, the circuit on the left in
It becomes more interesting when we make a graph of the current Figure 5: here a diode is connected via a series resistor of 1 kΩ to
through a diode as a function of the voltage across the diode. a DC voltage source. At a voltage of 7.5 V there flows a current of
Figure 3 gives an example. In such a V/I-diagram the voltage is 6.68 mA, and the voltage drop across the diode amounts to 0.715 V.
plotted along the horizontal axis and the current along the vertical We now double the input voltage (the power supply voltage) to
axis. As a comparison, Figure 4 shows a V/I-characteristic of a few 15 V. The current will obviously increase, to 14.12 mA, but the
ordinary resistors. With a resistor that has a small value this line voltage across the diode only increases a small amount, to 0.761 V.
is steep, with a larger value it is much more horizontal. Conclusion: when doubling the power supply voltage, the voltage
  across the diode increases by only about 6%.
When we look closely at Figure 3, we see that up to a voltage of 0.5 V  
barely anything happens — practically no current flows through When we use a ‘two-step circuit’ (Figure 5, right), the voltage is
the diode. Beyond 0.5 V the curve quickly becomes increasingly regulated even better. Using the three diodes in series a voltage
steep; the slope from this point onwards is mainly determined by of about 2 V is generated. With this already reasonably regulated
the internal resistance of the diode. voltage a second diode is powered.
   
For completeness, the curve of Figure 3 was measured using a Here, at an input voltage of 7.5 V we measure a voltage of 0.617 V
silicon diode of the type 1N4148, but the V/I-characteristics of across the second diode and at an input voltage of 15 V we measure
other Si-diodes show a very similar curve. a voltage of 0.662 V. So, a doubling of the input voltage (that is, an
increase of 100%) in this circuit results in an increased voltage
The Specifications of a Diode across the second diode of only 0.8%.
The manufacturer of a diode will at a minimum specify the  
maximum current capability in the forward direction and the Regulation of voltages using ordinary diodes is only used when

lektor May & June 2022 37


U(t)

Figure 5: Voltage Figure 7: Voltage U(t)

regulation with wave shapes for the


ordinary diodes. single-sided (half-
t
wave) rectifier.

U(t)

Figure 6: Single-sided t
(half-wave) rectifier.

we need very low voltages. For higher regulated voltages, we use


Zener diodes, which will feature in the next instalment. Contributors
Idea and illustrations: Michael Ebner
Power Supply Circuits Text and editing: Eric Bogers
One of the most important application of diodes is that of rectifier Translation: Arthur de Beun
in power supply circuits. Electronic circuits (devices) require a DC Layout: Giel Dols
voltage for their power supply that, depending on the device, can be
anywhere between 1.5 V and 150 V. However, the mains only supplies
an AC voltage of 230 V. This voltage therefore has to be transformed Questions or Comments?
to an acceptably low voltage first, and then has to be rectified and Do you have any technical questions or comments prompted by
smoothed, and in most cases will also need to be regulated. this article? Send an email to the editor via [email protected].

One-Sided Rectifiers
The term ‘one-sided’ (see Figure 6) has nothing to do with sides,
but means that only one half of the two half periods of the AC input
voltage is let through — and only the positive half period — and
then only for the relatively short time that the transformer output
voltage is higher than the voltage across the electrolytic capaci-
tor plus the forward voltage drop of the diode (which amounts to
about 0.7 V). This type of circuit is appropriately called a half-wave
rectifier. RELATED PRODUCTS
 
We have sketched this in Figure 7. The top graph shows the AC
voltage as it is supplied by the transformer. If we think away the > B. Kainka, Basic Electronics for Beginners,
Elektor 2020. (SKU 19212)
buffer or smoothing electrolytic capacitor for a moment, then
www.elektor.com/13950  
across the resistor (the load) there will be a pulsing DC voltage, as
is drawn in the middle graph. > B. Kainka, Basic Electronics for Beginners (E-Book),
  Elektor 2020. (SKU 19213)
www.elektor.com/18232
The bottommost graph is actually the most interesting. This
graph shows the voltage across the buffer capacitor. During the
positive half periods of the AC voltage this capacitor is charged very
briefly each cycle; during the remainder of the cycle the capacitor
is discharged by the load. In practice this load is generally not a
simple resistor but a complete electronic circuit that likes to be
powered from a DC voltage.
 
In the next instalment, we will start to calculate things for these
(and other) rectifiers.
220003-01

Editor’s Note: The series of articles “Starting Out in Electronics” is based


on the book Basiskurs Elektronik, by Michael Ebner, which was published
in German and Dutch by Elektor.

38 May & June 2022 www.elektormagazine.com


They trust us,
do you?

We love electronics and projects, and we do


our utmost to fulfil the needs of our customers.
The Elektor Store: ‘Never Expensive, Always Surprising’

Check out more reviewsw.on tor.com/TP


our Trustpilot page: ww elek
Or make up your own mind by
w.elektor.com
visiting our Elektor Store, ww
developer’s zone
Tips & Tricks, Best Practices and
Other Useful Information

Tips & Tricks


for Testing Components
No Expensive Equipment Required

By David Ashton (Australia)

In my article on component identification,


I touched on the importance of
component testing skills [1].
As a hobbyist, you usually just want to
verify that a component works before
soldering it into your circuit. There are a
number of techniques that can be used to Resistors
test components that have been stripped Digital multimeters are now so cheap and ubiquitous that there is
off boards or of otherwise uncertain little point in making your own testers. There are exceptions — very
low-value resistors (by which I mean under 1 Ω or so) used for current
provenance, from your spares box, sensing and other applications, cannot be reliably tested with cheap
that don’t need fancy or expensive test digital meters, as the resistance of the test leads is in the same ballpark
equipment. as the resistor to be tested.
 
A more reliable method is to put a known current through the resis-
tor and measure the voltage across it. There are many designs in

40 May & June 2022 www.elektormagazine.com


past Elektor articles and on the internet for milliohm meters, as they
are called, and some are simple and will give acceptable results for
a quick test.
 
Resistors that have got hot to the point of discoloring the body or Figure 1: A way to quickly test Zener diodes.
markings should usually not be kept but sometimes you may want to
test and keep them.

Transformers
Transformers are just a special case of inductors. Identify the windings
with a multimeter, then get the inductances. For a small power trans-
former, any winding with resistance above about 50 Ω and induc-
tance over about 10 H may be a mains winding. And as inductance is
proportional to the square of the number of turns, take the square root
of the ratio of the windings’ inductances to get the transformer ratio.
 
For example, a transformer with inductances of 10 H and 50 mH has
a turns ratio of around (10 / 0.05)0.5 = 14, so if it’s a 240 VAC mains
transformer, you’d expect the secondary to give about 15 V. But many
mains windings will have a higher inductance than your LCR meter
Capacitors and Inductors will measure, so you can’t always do this.
When I was about 20 (that was many years ago now), I built myself a
capacitance meter. A 555 astable triggered a 74121 monostable with
the test capacitor to give a pulse train with duty cycle proportional
to the test capacitor. I used a preset pot on each range and used 1%
capacitors to calibrate it. It measured from around 1 pf to 100 µF and
is one of the most useful gadgets I’ve ever built.
 
Many digital multimeters now have a capacitance test function, and I
found one in a recent electronics magazine for around €40 ($40/₤30)
that measures capacitance and inductance, albeit with fairly limited
ranges. I had a basic but adequate LCR meter that was about the same
price but recently invested in a more versatile one. You very much get
what you pay for with this type of test equipment and what you get
will depend on your budget and requirements. It’s really not worth
building your own testers anymore. But in some circumstances, you Diodes
may need to make more esoteric measurements, such as the Equiv- Diodes are easy to test with any multimeter — they conduct one way
alent Series Resistance (ESR) of a capacitor, or the Q of an inductor, and not the other. Digital multimeters may have a diode test range
and for this, you may need more advanced test equipment. Elektor and this will give you an indication of the voltage across the diode
has published many designs over the years for devices to measure all when conducting — around 0.6 to 0.7 means it is a standard silicon
aspects of capacitance and inductance and a search on the magazine diode, 0.3 to 0.5 means it is a Schottky diode, and as low as 0.2 means
site may lead you to a design that fulfils your needs. The Elektor store a germanium diode. The position of the decimal point may vary, but
has some reasonably priced testers as well (see textbox). it’s the first figure you need to look at.
   
Supercapacitors are just a special case of electrolytic capacitors but Zener diodes are a bit more difficult. They will behave as normal diodes
beyond the range of most testers. They are usually rated at 5.5 V, so when tested with a multimeter, as a multimeter is unlikely to apply
be careful not to exceed this. Test them using a resistor of 100 Ω to a enough voltage to make it conduct in reverse (Zener) mode. To test
5 V supply, and count the number of seconds for a fully discharged Zeners, use your lab power supply on its maximum voltage, with a
cap to get to 3.5 V. Divide that by 100 and you’ve got a rough estimate very low current limit (say 10 mA), or a series resistor that will pass
of the capacitance in farads. This uses the RC time constant — the around 10 mA at the full voltage. Apply this to the Zener and measure
time for the capacitor to reach 0.7 of full charge (5 V x 0.7 = 3.5 V). the voltage across it with your multimeter (Figure 1). This will only
A 1-F capacitor will take 100 Ω x 1 F = 100 seconds to get to 3.5 V. work for Zeners with voltages less than your power supply, but a 30 V
100/100 = 1, so 1 farad. power supply will cover most Zeners.

lektor May & June 2022 41


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

 
LEDs can be tested much like Zeners, but turn the power supply
voltage down to 5 V or so — LEDs have quite a low reverse break-
down voltage. Test any LED with a clear case both ways — it may be
a bicolor type. Limit the current to 10 mA; it is enough to make any
LED light and is safe even for small LEDs.

Transistors
When I was about 13, I saw an article somewhere for a simple transistor
tester, checking function and giving an Hfe (gain) value. It gave reason-
able accuracy on small-signal silicon transistors, but was inaccurate
for germanium transistors — hardly a problem these days! It has had
a lot of use and I still use it today. But again, most multimeters have a
transistor tester built in, and generally, they do a good job.
 
Bear in mind also that a transistor behaves as two diodes, so identi-
fying the base is fairly easy. Transistors like Darlingtons and power
transistors are more difficult to test as they need higher base-emitter
voltages or larger collector currents to do a proper test. But for the Figure 2: A simple Power Semiconductor Tester tests MOSFETs,
transistors, SCRs and Triacs.
hobbyist, a basic functional “go/no go” test is all that’s needed.

MOSFETs
MOSFETs have become ubiquitous, and a simple transistor tester will anode or the positive supply, the SCR should turn on (draw current)
not be able to test them. Most of them require gate-source voltages and continue to do so even after the gate drive is removed. You have
of 5 V or above to switch them on fully. Fortunately, there is an easy to interrupt the anode connection to switch it off. Triacs are the same
way to do a functional test of a MOSFET using only a current-limited but will work with the power both ways.
power supply (or a power supply and a resistor, or even better a light  
bulb) and your fingers or a high-value resistor (a megohm or so). The test requirements for MOSFETs, transistors, and SCRs are similar,
Putting the resistor (or your fingers) gate-to-positive should switch it and you can build yourself a basic tester that will test all of them. The
on and gate-to-source should switch it off. Because MOSFETs have one I built is shown in Figure 2.
appreciable capacitance on the gate, it may take a second or more to
switch off and on. Use 12 V to apply enough gate voltage, and limit the VDRs
current to 100 mA or less, or you may burn your fingers if the MOSFET Voltage-Dependent Resistors (VDR), sometimes called tranzorbs,
is not on a heatsink! and other surge protectors such as the gas types and the P6KE
semiconductor ones are among the more difficult components to
test. A 460-volt VDR will only start to conduct at over 500 V. But, if
you have access to an electrician’s megger or insulation tester, you
can do a quick check of these.
 
Most insulation testers have three test voltages: 250 V, 500 V, and
1000 V. A 460 V VDR should give no deflection or reading at 250 V,
some deflection at 500 V and show low resistance at 1000 V. Results
may vary with the model of tester used but should be good enough for
a go / no go test. Non-working VDRs are either shorted or completely
open-circuit, and this test will show either of those conditions. And
keep your fingers away from those voltages!

Polyfuses or PTC Resistors


These are devices that usually have low resistance (a few ohms), but
Thyristors/SCRs/Triacs when more than the rated current flows through them, they heat up
For these you can use the same setup as for MOSFETs above, except and go high resistance and will usually stay there until the source of the
that you will need a smaller resistor for the gate — around 470 Ω to overcurrent is removed. Test them by putting them on a current-limited
1 kΩ should be fine. When you connect the gate, via the resistor, to the power supply and slowly increasing the current. Initially, the voltage

42 May & June 2022 www.elektormagazine.com


across them will be small, but as the current increases, they increase
their resistance and the voltage across them will increase fairly fast. The TL866 Programmer & Digital IC Tester
Using this technique, you can get an idea of their rated current (which
will be less than the point that causes them to go high-resistance). And
don’t burn your fingers; they increase their resistance by getting hot!

DIP Switches
Used DIP switches may have some switches faulty so test them before
use. You can test any switch with a multimeter of course, but if you
have a lot of them to test, you can make a DIP switch tester with an
IC socket, resistors, and LEDs to indicate if each switch pole is open
or closed.
  Source: David Ashton
In addition, you can use it for testing LEDs. Put an LED where one of
the switch poles should be and both it and the tester LED should light  
if it’s good. One I built is shown in Figure 3. The TL866 is primarily a programmer of a very wide range of devices.
At this it seems reasonably competent and many reviews are avail-
Integrated Circuits able, including Elektor’s [6]. However, I will concentrate on its ability
These are more difficult to test, as there are so many varieties. But there to test Logic ICs.
are easy tests you can do. Op-amps usually have the same pinouts, so  
you can make a simple op-amp tester by configuring it to work as an The TL866-II – the current version - presents in a plastic case with
astable multivibrator with a couple of LEDs on the output. It will work a good quality 40-pin ZIF socket and a couple of LEDs, and a USB
for many comparators as well, but bear in mind that some comparators connection. I had to download the software from the manufactur-
only have a bare transistor on the output and will not source current. er’s site – something I’m not keen on, but it is the manufacturer’s
  site so the risk is not high. The TL866 has a good printable PDF
You could make testers for double and quad op-amps as well. Use manual. The software is fairly well laid out and you can quickly find
a decent quality socket — a Zero Insertion Force (ZIF) type if your most devices and functions.
budget runs to that. You can do the same for the much-loved 555 —  
have it running as an astable with LEDs on the output. In the Device tab on the main menu is the item Logic Test. This
  brings up a long list of CMOS 4000 and TTL 74 series IC types to
Digital ICs are more difficult. If you need to test these a lot, your best choose from, and even some Intel 8080 peripheral devices. I spent
course of action is to buy a suitable tester. There is a device called a happy half hour with my boxes of CMOS and TTL ICs trying a
the TL866 [2] (see inset), usually widely available at under $50, which good many of them and the TL866 tested most of them with no
is an EPROM programmer but also tests logic ICs. There are a few problems. However 74LS21s consistently brought up an error - a
different models available so look at the specifications before you buy. bit disappointing on such a basic IC.
The TL866II is the current version.  
But now for the fun part. The TL866 software displays the test
sequence it uses, and you can copy and edit them (though you
have to store them with a new name). Looking at the 7421 datasheet
and the programmed test sequence, I noticed that pins 3 and 11
had “H” (high level expected) marked for those pins. These pins are
not used, so they should be ignored. If I changed those pins to “x”
(ignore) the test worked, and I successfully tested all my 74LS21s
with no errors. I’m now confident I can test just about any digital
IC, even if I have to write my own test sequences for some of them.
Some other ICs gave errors, primarily monostable multivibrators
which would be difficult to test without timing components.
 
For testing SMD ICs, you can find sets of SMD-to-DIL adapters on
eBay and other sites, and in fact you can buy a TL866 with various
Figure 3: A DIY DIP Switch / LED tester shown testing a 4-way DIP adapters included for less than $50 – a very handy tester for a good
switch and a couple of LEDs.
price, and a good addition to any hobbyist’s collection of test gear.

lektor May & June 2022 43


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

 
They come with a ZIF socket for most sizes of through-hole ICs but
often come with handy adapters for testing various SMD package
components as well. Some models do ICSP programming if that’s
useful for you, but the newer ones don’t program very old EPROMs.
(For this old-timer, that’s important!) For just testing digital ICs neither
of those is very important. You can write your own testing programs
too, for ICs not in the database or those for which the included
programs don’t work (there are a few).

Quartz Crystals
Quartz crystals and oscillators are some of the more common compo-
nents you will find when stripping professional equipment. Usually,
these components are marked with their frequency and a simple go/
no go test is required. This can be done fairly simply. To verify the
frequency, or to test crystals that are not marked, a frequency counter
will be needed. You need only two inverting gates to make a crystal
oscillate, and another one to detect that it is oscillating. You can use
the 4th gate in a quad gate IC as a buffer to feed a frequency counter. Figure 4: Tweezer probe for multimeter. (Source: Sparkfun)
 
32,768-Hz crystals are commonly used in real-time clocks, but crystals
for microcontrollers are typically in the MHz region, so you may
need two oscillators to check all crystals. Then add a DIP socket
to check oscillators; you just need power and a connection to the
output. SMD crystals and oscillators are more difficult. You may 3-terminal semiconductor device and is highly recommended. If you
need a test jig for them. need to do more detailed tests than the simple tests outlined above,
it is worth investing in test gear like this. Elektor has recently started
Relays stocking the Joy-IT LCR-T7 Multi-function Component Tester [5]
Relays are still widely used. For isolation and high current handling which, while not offering the specifications of Peak’s tester, is about
they can’t be beaten. Test the contacts with a multimeter with a a quarter of the price and represents outstanding value.
continuity buzzer which will show low resistance, and operate the  
relay with your power supply set to the appropriate voltage and A desk or hand-held lens with LED illumination, and/or a USB micro-
make sure the contacts open or close. If you have a lot of relays of scope, is handy for checking small components for value, polarity,
one type it may be worth making a test jig for them, using a load of or orientation.
up to a few amps (e.g., a car light bulb) to weed out any with high  
resistance contacts. A power supply has been mentioned above in many of the tests. At
a minimum, a 0‑30 variable supply with a variable current limit of
Other Tools 10 mA or less up to 500 mA or more will be adequate.
If you can only afford one piece of good test equipment, make it a  
decent multimeter, with transistor test, capacitance, and other ranges Using these simple techniques and some DIY test gear will make
(frequency, temperature…). It will be really useful until you can buy your life a lot easier if you re-use components for your projects.
or build better test equipment. 210279-01
 
One of the most useful things you can buy if you do any SMD work is
a tweezer-style probe (Figure 4). This plugs into your test meter and Contributors
allows you to very quickly and easily test SMD resistors, capacitors, Text and Photographs: David Ashton
inductors, and diodes. They are made by Sparkfun and are widely Editor: Clemens Valens
available. You can get meters built into tweezers if you really do a Layout: Harmen Heida
lot of SMD testing. For example, the DT71 is available in the Elektor
Store (see textbox) and a good review is at [3].
  Questions or Comments?
Peak makes a line of “Atlas” hand-held component testers which have Do you have technical questions or comments about this article?
good reviews and are reasonably priced. In particular, their DCA75 Contact Elektor at [email protected].
Semiconductor Analyser (see inset) will identify just about any 2- or

44 May & June 2022 www.elektormagazine.com


Peak DCA75 Advanced small tester with only two buttons could them as Triacs. This alone convinced me
Semiconductor Analyzer be worth what it costs. that the DCA75 is worth its weight in gold!
Review The DCA75 does have some minor limita-
I could not have been more pleasantly tions – it cannot test Zeners and voltage
surprised, however. It does everything it regulators of above 8 or 9 volts – and will
claims and is simplicity itself to use. The not identify some of the more esoteric
interface is sheer genius and hardly needs semiconductor devices like Unijunction
you to do anything. You connect up your transistors, but these are not serious
device, any way you like, and the DCA75 drawbacks for the average user.
will identify what you have connected, give  
you some basic characteristics, and tell you Using a PC and the included USB cable
which lead is which. and software, the DCA75 can also produce
    characteristic curves of many devices. All
Try as I might I could not fox the DCA75. in all a really versatile bit of test gear to add
One of the first things I tried was a 0V8F to your arsenal. There is a small brother,
Some time ago I splashed out on a “transistor” from my article on Compo- the DCA55, at about half the price, but
Peak DCA75 Advanced Semiconduc- nent Identification [1]. I had not been able my advice would be to stump up for the
tor Analyzer. I was a little hesitant, I will to identify or test them- I thought they might DCA75. I cannot recommend this tester
admit, because I wondered how such a be FETs. The DCA75 instantly identified too highly.

RELATED PRODUCTS

> Peak Atlas DCA75 Pro Advanced Semiconductor Analyser


(SKU 17567)
www.elektor.com/17567  

> Miniware DT71 Digital Tweezers (SKU 19422)


www.elektor.com/19422  

> Joy-IT LCR-T7 Multi-function Component Tester (SKU


19709)
www.elektor.com/19709  

> Elektor 2 MHz LCR Meter Kit (SKU 19883)


www.elektor.com/19883

WEB LINKS
[1] D. Ashton, “Component Identification,” Elektor 3-4/2022 : https://www.elektormagazine.com/210024-01
[2] Review: MiniPro TL866A programmer: https://www.elektormagazine.com/news/review-minipro-tl866a-programmer/14585
[3] H. Baggen, “Miniware DT71 Digital Tweezers,” Elektor 7-8/2021: https://www.elektormagazine.com/210182-01
[4] H
 andheld Advanced Semiconductor Component Analyser: PEAK DCA75:
https://www.elektormagazine.com/news/handheld-advanced-semiconductor-component-analyser
[5] Joy-IT LCR-T7 Multi-Function Tester: https://www.elektormagazine.com/news/joyit-lcrt7-multifunction-tester
[6] Review: MiniPro TL866A programmer: https://www.elektormagazine.com/news/review-minipro-tl866a-programmer/14585

lektor May & June 2022 45


project

Reducing the Power


Consumption
of Your Mole Repeller
An ATtiny13 Replaces a 555

or-labs.co
kt
m
Ele

BEST OF
om

ek
t o r-la b s.c
El

By Gerhard Dürr (Germany) and Luc Lemmens (Elektor)

Mole hills can ruin your carefully manicured lawn in no time at all. If you guard your
precious garden with an electronic mole repeller, this hardware upgrade can increase the life
span of its batteries by a factor of 10!

If you have a garden with a lawn, especially if you live in a rural area, mole repeller: a device that uses (sound) vibrations to prevent or end
you run the risk of being unpleasantly surprised by the presence of these underground activities. It is a spiked tube that is inserted into
moles, or rather by the mole hills they make. The good news is that the ground; in the tip, there is a sound source (usually in the form of
you will most likely have clean, fertile soil in your garden. You will never an electronic DC buzzer) that is meant to chase away moles and other
— or rarely — see the animals themselves, as they usually stay under- vermin like voles and rats.
ground in tunnels that they dig, looking for worms and insects that are  
on their menu. The soil that they move during their digging has to go Some manufacturers claim that the pest repellers they make are
somewhere, of course, and they push it upwards and thus form mole producing ultrasonic vibrations. Maybe they do exist, but most devices
hills, the sign that there is a mole in (actually: under) your garden. Not we found – according to their specifications — produce sounds with
many people are happy about this, and numerous methods have been frequencies in the low kilohertz region or even lower, which is way
devised to prevent moles entering a garden or to chase them away below the ultrasonic range. In most cases, the term sonic repeller
once they have settled there. One of the solutions is the so-called (without ultra-) will be more appropriate. The sound is switched on

46 May & June 2022 www.elektormagazine.com


K4

K1 K5
+6V +6V
D2
D1 R3
Buzzer

10k
LL4148
RED
K2
6 T1 K6
D
IC1
for about half a second, at intervals of some 30 seconds. These pulses 5 8
VCC RESET
1
R1
G
would be so unpleasant for a mole that it would pack up and/or stay
4 7 2
PB2/SCK PB3/AD3 220
ISP 3 6 3

away. There are people who are absolutely convinced of the effec-
PB1/MISO PB4/AD2 S
2 5 4 GF2304
PB0/MOSI GND

tiveness of these devices, others claim they are just a scam and that
1
ATtiny13A

only the manufacturers and sellers benefit from them; we will not
C1 C2 R2

220k
comment on that. K3
100µ 470n
10V
  GND

Some thoughts on mole repelling in general are shared in the text


200653-009

box. In this article, we will only discuss a way to reduce the power
consumption of a battery-powered, sound generating variant. Figure 1: The circuit diagram of the upgrade of the time circuit.

How It Works
This type of repeller contains a timing circuit and some kind of
sounder; the latter will be a piezo buzzer in most cases, but we have
also found devices with vibration motors, like the ones used in cell
phones. In electronics, anyone who says “Timer circuits” immediately
says “555”, perhaps the most famous integrated circuit that recently
celebrated its 50th anniversary. There will be exceptions, but the
designer of the circuit we are discussing here also came across a
mole repellent in which the 555 was used as a bistable multivibra-
tor. Most of the power of the device is consumed when the sound is
being produced, but of course some power is also needed to keep
the 555 running when the buzzer is switched off. Although tweaking
this circuit may save power and thus extends the battery life (e.g.,
by replacing a standard 555 by a CMOS-version or by changing the
values of its external components), the designer chose a different
approach. The complete timer circuit is replaced by a small micro-
controller that stays in sleep mode most of the time; its watchdog
timer wakes it up approximately every half minute and sounds the Figure 2: The PCB layout.
buzzer for one second and then enters sleep mode again. The current
consumption is reduced with nearly a factor of ten: 4 mA with the
original 555 timer circuit versus an average of 430 µA with the micro-
controller, or a battery life of less than 200 days extended to about
1450 days! In practice this will be shorter, due to factors such as three standard 1N4148 diodes in series. A linear voltage regulator
self-discharge of the batteries, but still, this is a great improvement should not be used for this purpose, as it would increase the current
compared to the original current consumption of the mole repeller. consumption of the mole repeller. C1 and C2 are decoupling capac-
itors for the power supply of the microcontroller.
The New Hardware  
The schematic diagram of the microcontroller circuit is shown in The buzzer is salvaged from the original hardware and connected to
Figure 1. IC1, an ATtiny13 from Microchip (formerly Atmel), is the heart the K4/K5 (positive) and K6 (negative) pins. Some buzzers are induc-
of the timer circuit. Its internal program memory can be flashed with tive and likely to produce spikes, especially when switching off. Diode
an ISP programming interface connected to K2. Alternatively, this D2 is the flyback-diode that prevents these spikes from harming the
6-pin can be omitted if the microcontroller is programmed before it transistor T1. The choice of this switching transistor is not critical at
is inserted in the socket for IC1. all. With the current through the buzzer being less than 10 mA, also a
  standard BC547 can be used if base resistor R1 is changed to 4.7 kΩ
The circuit is powered by the batteries, in this case four D-cells in and R2 to 10 kΩ. Any logic-level NMOS-FET will do too, with R1 replaced
series — i.e., 6 V in total connected to K1 and K3 (the positive and by a jumper wire and R2 omitted.
negative terminals, respectively). With four freshly installed 1.5 V
batteries, with no load or very low load connected, the total voltage There Is Even a PCB Design
will be higher, more like 6.5 V. However, the ATtiny13 has an absolute The schematic was designed in a free version of Target3001!, and the
maximum supply voltage of 5.5 V. D1 is a standard red LED (preferably author even made a small PCB for the microcontroller upgrade (see
not a high-efficiency type) which has a forward voltage of about 1.3 V, Figure 2). The design files are available for download at the Elektor
even at a forward current as low as 1 µA and this effectively lowers Labs page of this project [1]. Considering the large number of different
the supply voltage to a safe value, well below the 5.5 V maximum brands of mole repellers available on the market, it would be a mere
for the microcontroller. Alternatively, D1 can be replaced by two or coincidence if the PCB exactly fits into the model you have like in

lektor May & June 2022 47


Figure 3a: Overview.

Nothing Runs Without Firmware


The source code (Listing 1) for the ATtiny13 is developed in AVR
Studio 4.19 with AVR-GCC compiler installed. Although this IDE is
outdated, it is still available for download, but it won’t be difficult to
adopt the source to more modern development tools. The source code,
the AVR Studio project and the HEX file can be downloaded from the
Elektor Labs page associated with this project [1]. The latter allows you
to flash the program memory of the ATtiny13 without compiling. The
configuration fuses of this microcontroller will stay at factory default
(i.e., they don’t need to be programmed).
Figure 3b: The new PCB installed inside the original mole chaser.  
The program largely consists only of assembly statements, written in
C. After power on, the GPIOs are configured and the timers, the ADC,
the pull-ups, the analog comparator are switched off, and the sleep
the pictures the authors made (Figure 3). For many of us, it will be a mode is set to Powerdown. The code then enters an endless loop
nice opportunity to try and test Target3001! with this relatively simple (while(1)), which performs the following operations:
project if you want to change the PCB, but it will also not be too diffi-  
cult to redraw the schematic and circuit board if you prefer to use any > The buzzer is switched on.
other CAD program. There are a few SMD components soldered on > The watchdog is set to generate an interrupt after 128k cycles,
the copper bottom side of the PCB that can easily be replaced with with a 128 kHz clock this gives a one second interrupt interval
through-hole parts even without changing the PCB. (approximately).
> The interrupt is enabled and the ATtiny switches to Powerdown
mode with the assembler command sleep.
> After one second, the watchdog interrupt wakes up the micro-
Moles in Your Garden? What (Not) to Do? controller from Powerdown.
If you search on the Internet what you can do about moles in your > The buzzer is switched off and the watchdog interrupt is changed
garden, or how you can prevent them from coming to your property to its maximum interval of 1024k cycles, i.e. 8 seconds. Since we
in the first place, you will be surprised what, over the years, has want the repeller to be silent for approximately half a minute, the
been invented to make life difficult for these creatures. Many of watchdog must generate three interrupts before the while(1)
these remedies are doubted by (experience) experts as to their starts again with switching the buzzer on.
effectiveness. You only know for sure that such a method does not
work when — in spite of everything — your beautiful, flat lawn is No More Moles?
suddenly marred by mole hills. With this upgrade of the mole repeller, the battery life of the four
  D-cells is extended. It will not change the effectivity of the device
We are certainly no mole experts, but according to the information itself. As mentioned, there are many discussions between people who
we have found, doing nothing at all seems to be the best advice. think these mole repellents are great and others who believe or even
If there are molehills, a mole has already made his burrow and it know for sure that they have no effect at all. The large number of
will usually only expand if there is not enough food. If you find the brands and sellers suggests that a lot of people do believe in them
mini-mountains disturbing, the best thing to do is to carefully shovel and whether they really work or not. In any case, it is a remedy that has
away the soil; if you knock or pound them, the mole’s passage will no negative effects on the environment. The most negative thing we
collapse and there is a good chance that the animal will repair the found were reports of complaints from neighbours who are bothered
damage and make a new mole hill in the process. by the repellers’ repetitive, soft sounds.
200653-01

48 May & June 2022 www.elektormagazine.com


COMPONENT LIST Listing 1: The complete source code.
Resistors
R1 =220 Ω // Controlling the molechaser-buzzer with the watchdog-timer
R2 = 220 kΩ // * MC ATtiny13A, all fuse bytes default
R3 = 10 kΩ // * PB3 and PB4 HIGH: buzzer ON
  // * Configurable with watchdog-timer-prescaler
Capacitors // * Selected: 128K-cycles(~1s) ON, 3*1024K-cycles(~24s) OFF
C1 = 220 µF/25V // * Current consumption: powerdown ~6µA, buzzing ~7.2mA, average 0.43mA
C2 = 470 nF #include <avr/io.h>
  #ifndef F_CPU
Semiconductors #warning "Defining F_CPU 1.2MHz"
D1 = red LED #define F_CPU 1200000UL
D2 = LL4148 #endif
T1 = GF2304 (see text) #include <avr/interrupt.h>
IC1 = ATtiny13A (DIL-8 style) int main(void) {
    uint8_t i=0;
Miscellaneous  DDRB  = 1<<PB0|1<<PB1|1<<PB2|1<<PB3|1<<PB4;
K2 = 6-pin SIL header  PRR   = 1<<PRTIM0|1<<PRADC;         // Power Reduction Timer0, ADC
 MCUCR = 1<<PUD|1<<SE|1<<SM1|0<<SM0; // Pullup Disable, Sleepmode: Powerdown
 ACSR  = 1<<ACD;                     // Analog Comparator Disable
  while(1) {
    i = 0;
   PORTB |= 1<<PB3|1<<PB4;      // buzzer ON
Contributors // change Watchdog-Interrupt to 1s (measured: 1.14s @ 4.5V, 22°C)
Design: Gerhard Dürr    MCUSR  = 0;                  // clear Reset-Flags
Text: Gerhard Dürr,    WDTCR  = 1<<WDCE |0<<WDE;    // Watchdog Change Enable
Luc Lemmens // Watchdog Timer Prescaler: 128K-cycles(~1s), Watchdog Timer Interrupt Enable
Illustrations: Gerhard Dürr,    WDTCR  = 1<<WDTIE|0<<WDE|1<<WDP2|1<<WDP1;
Patrick Wielders, Luc Lemmens    sei();
Editors: Jens Nickel, C. J. Abate    asm volatile("sleep"::);
Layout: Giel Dols    asm volatile("wdr"::);       // Watchdog Reset, wait for WDT-ISR(~1s)
   PORTB &= ~(1<<PB3|1<<PB4);   // buzzer OFF
//  change Watchdog-Interrupt to  3*8s: (measured: 27.9s @ 4.5V, 22°C)
   asm volatile("wdr"::);       // Watchdog Reset
Questions or Comments?    MCUSR  = 0;                  // clear Reset-Flags
Do you have technical questions or    WDTCR  = 1<<WDCE|0<<WDE;     // Watchdog Change Enable
comments about this article? Email // Watchdog Timer Prescaler: 1024K-cycles(~8s), Watchdog Timer Interrupt Enable
Elektor at [email protected].     WDTCR  = 1<<WDTIE|0<<WDE|1<<WDP3|1<<WDP0;
    while(i < 3) {               // wait 24s
      i++;
      asm volatile("sleep"::);
      asm volatile("wdr"::);     // Watchdog Reset, wait for WDT-ISR(~8s)
    }
  }
}
EMPTY_INTERRUPT(WDT_vect);       // awaking from powerdown-mode

RELATED
PRODUCTS

> Diamex EXA-Prog Package WEB LINK


(SKU 19912) [1] This project on Elektor Labs: https://bit.ly/3JWCXBk
www.elektor.com/19912

lektor May & June 2022 49


project

b•
or la Elekt
kt

or
Ele

lab
ORIGIN
AL

Ele

b
or

kt
or

la
la b
• Ele k t

Light Switch DeLux


A Solution for High-Precision Light-Controlled Switching

By Clemens Valens (Elektor)


for this is the eye’s logarithmic response
to brightness. On a cloudy day brightness
Light-controlled switches are plentiful and retail can vary between 5,000 and 10,000 lux, yet
it looks almost the same to us. Sunlight may
for €10 or so, but most of them are changing their result in levels of over 25,000 lux, which we
state somewhere in the twilight zone. Sometimes notice, obviously, but we don’t experience
applications require better precision and more it as three or more times as bright.
 
control than these cheap switches allow for. Do you Plants, on the other hand, are way more
need a lux-accurate light control? If so, this project is sensitive to light intensity than humans.
for you. Farmers know this, and they shine artificial
light on some of their crop even during the
day to improve its yield. On sunny days this
is usually not needed, but on cloudy days
There exist many, many designs for light-con- is not true. The reason is that they all lack it may help. To do this in an economical
trolled switches and most of them work precision. Based on an LDR or phototrans- way, they therefore need light-controlled
great in the application they were designed istor, they tend to switch somewhere in the switches that can detect brightness differ-
for. These applications usually consist of twilight zone. However, light levels vary ences with more precision than an LDR or
switching on a light when the ambient light much more than that. phototransistor can do.
level drops below a certain threshold and  
switch the light off again when the light level Brightness Is Subjective Today light sensors exist that convert
increases. Sometimes a timer is added too. To humans, daylight intensity or bright- brightness directly to a value in lux with
  ness is fairly constant. Of course, we notice resolutions of up to 16 bits. Some of these
You might think that every possible applica- variations due to clouds and the sun, but we sensors not only measure lux, but also
tion is covered by these designs and yet this are not very sensitive to them. The reason UV and white light intensity. With such a

50 May & June 2022 www.elektormagazine.com


sensor, it is quite easy to build a high-pre- the same order as the OLED display connec- platform now must be custom. This tells
cision light-controlled switch. tor on the thermostat, and so we can stick ESPHome that you will provide all the
the module on K9. Make sure the VIN pin details for it.
High-Accuracy Ambient Light remains unconnected and the module  
Sensor points upwards (as opposed to how the Next follows a lambda section which
A popular light sensor is the VEML7700 OLED display would be plugged, see consists of a few lines of C++ code to tell
from Vishay. This is a high-accuracy Figure 1). ESPHome to register a sensor of our own
ambient light sensor with I²C interface and devising (that we named veml7700). We
it can be found mounted on a small module Software With ESPHome must also specify the data stream(s) that
for a few euros. From the same family we After connecting the sensor to the ESP32, our sensor produces. In this case it has
might also cite the VEML6075, a UVA and we must produce some software to make three outputs: ALS, lux and white light. The
UVB light sensor also with I²C interface. it all work. As the objective is some sort order is important and must be respected
  of light-controlled switch, a logical choice whenever they are referenced elsewhere
Because of its digital I²C interface the would be to use a home automation in the YAML file.
sensor does not need an analog-to-digital platform and my favorite is ESPHome.  
converter and can instead be connected Elektor has published several projects We continue with normal YAML statements
directly to most microcontrollers. Its output that used ESPHome [3][4], and so you may to further specify the sensor outputs. This is
data is available in two 16-bit registers: already know how to use and configure it, done with a sensors section (plural!) where
ambient light (also called ‘ALS’) and white but this project introduces a concept that we can specify for each data stream its
light. White light covers a wide spectrum I didn’t treat before: creating a custom name, its units and how many decimals to
from 250  nm up to 950  nm. The ALS sensor. If you are new to ESPHome, I recom- use. The order is the same as in the return
spectrum is much narrower, from about mend reading and watching [3] and [4] first. statement in the lambda section.
450 nm to 650 nm as it is optimized for  
human perception. Plants are not human, We Need a Custom Sensor Only the lux stream has units (‘lx’), and
so the output to use will depend on the ESPHome supports many sensors, but (at there is no point in having decimals for
application. the time of writing) not the VEML7700. It any of them, so we set them to zero.
  knows of other lux sensors, but not this one.  
Sensor sensitivity is important too. The However, this is not a problem as ESPHome The last thing to be done is to indicate
VEML7700 has a resolution of 0.005 lx offers a method of adding your own sensor. where ESPHome can find the driver for the
per LSB and a maximum detection level Doing so involves writing some C++ code, custom sensor. We do this in the esphome
of 167,000 lx (minimum is 0.01 lx). Such so it makes things a bit more involved. section at the top of the configuration file
a wide range would require 25-bit values,   where we add a file (veml7700.h) to the
but the device is only 16 bits; therefore, As before (see [3] and [4]) we must declare includes subsection. On the system that
a sensitivity value can be specified a sensor section in the ESPHome config- runs ESPHome, this file should be in the
(sometimes called ‘gain’) to bring things uration file for this device. The sensor’s same folder as the device’s YAML file.
into range. Its high sensitivity allows the
sensor to be used behind low transmit-
tance (i.e., dark) surfaces and still obtain
usable results.
 
For low-light conditions, the sensor
features an integration setting of up to
800 ms. Finally, low and high thresholds
can be set that can trigger interrupts,
making it easy to create alarms or allow
for automatic switching.

Stick It on an ESP32
The VEML7700 module used for my exper-
iments was bought at Adafruit. A good
platform to use it with is the ESP32-Con-
nected Thermostat [1] (a.k.a. Automator,
see [2]). The module has five pins, but as
it has two power supply options, we only Figure 1: The 5-pin VEML7700 module plugs onto 4-way connector K9. Its VIN pin is not
need four of them. These four pins have connected even though it may look like it.

lektor May & June 2022 51


The Hard Part return statement in the lambda subsection ESPHome would probably be more than
Done? Not really. Now comes the hard part, of the sensor section (see above). happy to let you do it, but the underlying
which is, of course, creating the driver for   Arduino Wire library doesn’t allow this.
the custom sensor. This driver must comply As our class inherits from the PollingCom-
to ESPHome standards for components ponent class which itself inherits from the Done
(a sensor is a component), meaning that Component class, other functions are avail- Here ends this article. If the Automator is
it must provide certain functions that able that you might want to use. A polling programmed by ESPHome with the code
ESPHome expects from its components, component is a component that is called described above, you will get a device that
and it must communicate with the sensor periodically, and the call rate can be speci- can be controlled from a home automation
itself. fied (e.g., in our constructor). Refer to [6] controller like Home Assistant (or by itself).
  for more details. There are no automation rules inside the
For the second part, we can rely on Adafruit ESPHome YAML file, so without a control-
who, besides manufacturing the VEML7700 Adding the I²C Bus ler it will just measure ambient light inten-
module, also created an Arduino library for The one thing that remains to be done sities. Automation rules can be added to
it [5]. Our driver must provide the interface now is connecting the sensor to the I²C the YAML file itself, or they can be created
between ESPHome and the Arduino library. bus inside the software (i.e., create a logical inside e.g. Home Assistant. For a descrip-
connection between the two, as we already tion of the rest of the YAML code, which is
Installing a Third-Party Library have a physical connection). The Adafruit nothing special, please refer to [3] and [4].
ESPHome provides a mechanism for adding library uses Arduino’s Wire library for this  
open-source community libraries: simply purpose. In the ESPHome YAML file, we The YAML configuration file and C++ code
add the exact (!) name of the library to the therefore add an i2c section so ESPHome is available for download from this article’s
libraries subsection in the esphome section. knows that it is needed. the webpage [7]. 
In our case this is “Adafruit VEML7700   210190-01
Library”. Now, when ESPHome processes The ESP32 has two I²C buses with SDA
the configuration file, it will first install and SCL signals that may be connected Contributors
the library (if it didn’t do so already, see to almost any pin on the chip. ESPHome Design, Text and Photographs:
Figure 2) before compiling everything. In therefore supports multiple I²C buses with Clemens Valens
your custom driver, you can simply include freely assignable pins, making it a matter Editor: Jens Nickel, C. J. Abate
the library as any other library. of specifying what goes where. But the Layout: Giel Dols
  Arduino Wire library supports only one
I haven’t pushed this feature too far, so I I²C bus, so how do you tell it to use the bus
don’t know the criteria a third-party library you want? Well, you can’t, as it will always Questions or Comments?
must fulfill to be used this way. You may use the default bus. In ESPHome the default Do you have technical questions or
want to consult the platform.io documen- I²C bus is the first bus specified in the i2c comments about his article? Email the
tation for more details as it is the toolchain section. It would have been nice to be able author at [email protected]
used by ESPHome. to specify an I²C bus by using its ID, and or contact Elektor at [email protected].

An Encapsulated Arduino
Sketch
Our driver is a C++ class that must provide
at least a constructor and a function named
update. We need a function setup too so
that we can initialize the Adafruit driver.
The functions setup and update of our
class do what would normally be done in
the functions setup and loop of a typical
Arduino sketch using the Adafruit driver.
Basically, our class encapsulates an Arduino
sketch including global variables and adds
some ESPHome-specific things to it. For
ESPHome we must insert calls to publish_
state for each data stream (ALS, lux & white
light) to the function update. This will make
the data available to the rest of the world. Figure 2: ESPHome installs the Adafruit library automatically.
The call order must be the same as in the

52 May & June 2022 www.elektormagazine.com


Some Results

dips are caused by clouds. The shadow of the house starts to


cover the sensor at 6 PM, which explains the steep fall. Then light
intensity continous to decrease until dark. For humans 5,000 lx
is already bright.

The light sensor placed in bright summer sunlight. At noon, with


sensitivity set to 0.125 and an integration time of 100 ms, the sensor
reported values of around 48,000 for ALS and a bit more than On a partly cloudy day in May brightness levels may be anywhere
30,000 for white light. These values correspond to light intensi- between approximately 4,000 and 27,000 lx. 
ties of around 22,000 lx. At 10:30 AM with the same conditions, I  
measured 16,800 lx, a difference of 5,200 lx. However, to my eyes All graphs were created with the help of Home Assistant at a
the brightness looked pretty much the same in both situations. latitude of 47°N.

RELATED PRODUCTS

> ESP32 DevKitC (SKU 18701)


www.elektor.com/18701  
> 0.96“ 128×64 I2C OLED display (SKU 18747)
www.elektor.com/18747  
Evolution of brightness on a sunny day in July. The “bouncing” > Koen Vervloesem, Getting Started with ESPHome
on the left is due to the shadow of a tree. From noon to 6 PM the (SKU 19738)
brightness slowly decreases but you wouldn’t really notice it. The www.elektor.com/19738

WEB LINKS
[1] Y. Bourdon, “ESP32-Connected Thermostat,” ElektorMag 9-10/2021: www.elektormagazine.com/200497-01
[2] Elektor Automator: www.elektormagazine.com/labs/automator
[3] ESPHome starts here: www.elektormagazine.com/labs/how-to-home-assistant-esphome
[4] C. Valens, “Home Automation Made Easy,” ElektorMag 9-10/2020: www.elektormagazine.com/200019-01
[5] Adafruit VEML7700 library: https://github.com/adafruit/Adafruit_VEML7700
[6] ESPHome on GitHub: https://github.com/esphome
[7] Downloads for this article: www.elektormagazine.com/210190-01

lektor May & June 2022 53


background

The Challenges in Bringing IoT


Solutions to Market
Worries Around Security, Scalability, and Competition

Figure 1: The European Commission has examined


whether the big players in voice assistants, the
favorite user interface to the smart home, are stifling
competition. (Source: ShutterStock/Gorodenkoff)
By Stuart Cording (Elektor)

The Internet of Things (IoT) has been around


for more than 20 years, and a host of wireless
technologies have sprung up to support its
deployment. In the home, voice assistants If you want to get a feel for the technologies behind the Internet of
Things (IoT), finding a raft of suitable projects doesn’t take long.
have established themselves as the primary Just search for “IoT” and you’re preferred prototyping platform,
user interface to an array of smart devices. and you’ll be overrun with pages of projects, cloud platforms,
Despite these advancements, more than a technology comparisons, and lists of ideas. Elektor is also a great
source of information. Since the term IoT was coined more than
third of IoT projects never make it past the 20 years ago, our website has collected more than 600 articles
proof-of-concept phase. Furthermore, the on or related to the topic [1].
European Commission is concerned that
a lack of competition in some application
spaces may be hindering market entry for EU
businesses. So, what are the real challenges,
and what is it like to deploy an IoT solution
across Europe?

54 May & June 2022 www.elektormagazine.com


ELEKTOR INDUSTRY

However, there is a considerable gap between a prototyped Little Room for Voice Assistant Newcomers
platform that demonstrates the core concept of an IoT solution With such powerful industry players already established on the
and deploying one for real. The IoT Insights report from Micro- market, there is little room for newcomers, and the technology
soft [2] interviewed more than 3,000 IoT professionals in 2021. curve to develop a competitive VA is significant. Thus, if you
They found that 35% of IoT projects experience failure during the want to leverage voice control for your IoT solution, you have to
trial or proof-of-concept phase, up 5% on their survey from a year play according to the rules set by the big three. An alternative
earlier. Most cited as the reason for failure at this stage is the high approach would be to license a VA. However, some manufactur-
cost of scaling. Other reasons include too many platforms to test, ers questioned reported that licensing conditions were restrict-
too many use cases to prove, and a lack of resources. A separate ing their choices. These ranged from exclusivity or restrictions
study by Cisco [3] reported that only 26% of companies surveyed to stop more than one VA being used concurrently to licensing
thought their IoT initiatives had been successful. Responses to that forced the inclusion of other types of software or applica-
their study showed that, while most IoT projects look good on tions, meaning the VA technology couldn’t be used standalone.
paper, they proved to be more complex than initially thought.  
  Another big concern is access to data. As a third party relying
Despite such gloomy feedback on IoT overall, there are sectors on a VA, you only have limited access to the data collected.
where IoT is making huge inroads and delivering growing The VA provider has access to the audio recordings and would
revenues. also know how many failed attempts there
have been to issue the commands selected
EU Commission Reviews for your device. However, your team will not
Consumer IoT Sector be provided access to the audio recordings,
EU citizens have welcomed the range of so you’ll more likely have to wait for user
consumer IoT solutions on offer in recent feedback to discover that your choice of
years. So much so, a Smart Home revenue Looking at the available voice commands is suboptimal amongst
report from Statista [4] predicts that related IoT landscape, it is a group more expansive than that used
revenues will double from around €17b in for testing. Additionally, because the VA
2020 to around €38.1b in 2025. Concerned clear that business provider can analyze everything spoken into
that competition in this sector may be being opportunities abound, it, they could conceivably use this data to
stifled, the European Commission under- develop a solution that competes with yours
took an inquiry as part of their digital strat- regardless of whether or leverage user experience provided by your
egy [5]. The report, released in January of you are focused on IoT solution to improve their services.
2022, garnered input from manufacturers  
of wearable devices, connected consumer solutions for consumers A further issue arises when the VA provider
devices used in the smart home, and those or industry. also offers advertising services. Theoreti-
providing services over such smart devices. cally, the voice input provided by your users
Additionally, the Commission requested input could help the provider target advertis-
from standard-setting organizations. However, upon reading, ing more accurately to the demographic represented by your
many paragraphs of their analysis are given to the voice assis- customer base.
tants (VA) that form the user interface to many IoT products and  
services (Figure 1). Finally, there is the loss of brand recognition and experience.
  Your carefully crafted solution is at the whims and mercies of
Having analyzed the landscape of the smart home, the report the VA. Should they choose to make a significant change, such
[6] makes it clear that, in Europe, Google’s Google Assistant, as the voice used, the wake word, or even roll-out functionality
Amazon’s Alexa, and Apple’s Siri are the leading general-pur- changes that result in a drop in users, you’re inevitably going
pose VAs. Other VAs are available, but these tend to be more to suffer the consequences too.
limited in functionality and focus on supporting a single product  
or a service provider’s app. According to ZDNet, of the solutions The report also examines many other relevant areas, including
from the big three players, Amazon provides the highest level of application programming interfaces (API), standards, interop-
compatibility, supporting around 7,400 brands [7]. By compar- erability, the imbalance in power between many third-party IoT
ison, Google supports around 1,000, while Apple remains the device developers and the big cloud platform service providers,
most exclusive, supporting about 50. and contract termination clauses.

lektor May & June 2022 55


Figure 2: Researchers
discovered a Denial-of-Service
(DoS) attack in LoRa 1.0. By
replaying a previous successful
data transfer, a LoRaWAN
node is hindered from sending
further data packets. (Source:
Trend Micro)

 
There are no recommendations in the report. However, the LoRaWAN Under the Magnifying Glass
conclusions state that the report’s content will contribute to LoRa and LoRaWAN have been subject to particular scrutiny by
the Commission’s standardization strategy and feed into the the security and hacking community. Sébastien Dudek of Trend
legislative debate on the Digital Markets Act (DMA). Micro, a company focused on IT security solutions, is one of several
researchers that has written extensively on some of the potential
Security Concerns Worry IoT Implementers issues. In a series of three technical briefs [9][10][11], he outlines
Reviewing the data collected in Microsoft’s IoT Insights report, a range of issues in the implementation and potential attacks.
it is IoT security that is high on the list of worries. This issue These range from denial of service (DoS) (Figure 2) and eaves-
is of particular concern for those planning IoT solutions, with dropping to bit-flipping (Figure 3) and spoofing of acknowledg-
29% indicating that the associated security risks are holding ments (Figure 4). The outcomes of such attacks range from the
them back from using IoT more. The report also explains that inability to communicate with nodes and reducing the battery
around a third of organizations are concerned about the security life to altering application data.
risks of IoT, especially data breaches. To combat this, outsourc-  
ing is highlighted as the best way of improving peace of mind. Many of the vulnerabilities highlighted were resolved between
  version 1.0.2 and 1.1 of the LoRaWAN standard. However, further
While many engineers know the phrase “obscurity is not challenges arise when operating LoRaWAN nodes with gateways
security,” few are skilled enough in this domain to ensure a using different versions of the specification. In such cases, there is
solution is protected, end-to-end, from attackers. And while a need to make modifications to ensure secured backward compat-
semiconductor suppliers offer a range of single-chip security ibility between end devices and the back-end, as highlighted in
solutions, developers still need to understand how to use them a paper from 2018 by Tahsin C. M. Dönmez [12].
correctly to ensure that they don’t inadvertently introduce new  
security weaknesses. Beyond hacking the wireless link, there is also the issue of bad
  actors stealing and directly attacking the hardware. Sébas-
Over the past decades, low-power wide-area networks (LPWAN) tien Dudek also examines this aspect of security. In the case of
solutions such as LoRa and Sigfox have established themselves LoRaWAN, many solutions use a microcontroller (MCU) and a
as key wireless IoT technologies supporting long-range commu- Semtech wireless module. As these are connected via SPI, data
nication. Achieving ranges of tens of kilometers, they are an passing between the two can be easily captured and analyzed.
alternative to cellular wireless such as LTE Cat-M1 and NB-IoT  
thanks to their superior low-power performance for low data Beyond this, there is also the issue of the security of the MCU
volumes [8]. But how secure are they? itself. One attack method simply extracts the firmware from flash

56 May & June 2022 www.elektormagazine.com


Figure 3: Due to the known fixed structure of
LoRaWAN data packets, it is possible to flip
bits (bit-flipping attack) in the content without
having to decrypt the message. This requires
access to the network server receiving the data.
(Source: Trend Micro) Figure 4: Jamming the wireless link results in the LoRaWAN
node repeating the packet transfer up to seven times,
reducing battery life. If the attacker also captures and
replays acknowledgment packets (ACK), the node thinks
the link is still functional as ACK packets don’t declare the
message they are acknowledging. (Source: Trend Micro)

memory, allowing the code to be analyzed. If the security keys


are also in the firmware, an attacker can use them to develop
nodes that spoof authentic end devices. The recommendation
to counter this is the use of Secure Elements (SE), single-chip
authentication devices that securely store encryption keys. An
approach using Microchip’s ATECC608A [13] is one of several for
which example code is available. However, while example projects
demonstrate how to protect the cryptographic keys, the secure
boot feature of this authentication device is not used. Thus, if
the same approach were used for a product, the authentication
device could be removed and used as an SE with a different MCU
and new firmware.

Security Issues Across the Board


LoRaWAN end-devices provide only limited data bandwidth
and, as they have no IP address like a Wi-Fi module, they are
not addressable. As such, they offer minimal risk to corporate
networks. However, potential risks lie with applications based
upon such wireless technologies. These can have implications
on lives and the environment should something goes wrong.
For example, as part of a smart city network, LoRa-based sensors
may be responsible for monitoring water levels to avoid flooding.
If the data from the sensors are blocked, flood defense systems
may not respond. Conversely, false injected data could result in
flood defenses responding to an event that isn’t happening with
potentially equally disastrous consequences.
 
And while LoRa and LoRaWAN have been highlighted here, plenty Figure 5: DEUS POLLUTRACK particulate matter sensors gather data from
of researchers are examining other LPWAN technologies, includ- stationary and mobile IoT units. Data is delivered to the back-end using 4G
ing Sigfox and NB-IoT. In a paper by Florian Laurentiu Coman et and 5G cellular networks. (Source: DEUS POLLUTRACK)

lektor May & June 2022 57


Figure 6: A cloud-based dashboard shows the level of airborne pollutants, as shown here for the German city of Hamburg. Local authorities use
such data to make decisions on transportation solutions. (Source: DEUS POLLUTRACK)

al. [14], several proof-of-concept attacks on wireless networks in the delivery vans of DPD, that are already frequently underway
addition to LoRaWAN are described. In a technical brief issued by in the target city. These sensors recalibrate themselves against
Deutsch Telekom [15] it was stated that implementing Sigfox and data acquired by the stationary sensors they pass to ensure the
LoRaWAN “without [an SE] can [even make] end-to-end encryp- accuracy required based. All this requires a robust, reliable, and
tion useless.” It explains that, by contrast, NB-IoT benefits from secure LPWAN choice.
long-proven LTE security features, such as authentication and  
secure key generation and exchange. However, it also makes clear Talking to co-founder Marc Nodorft, he explains that both Sigfox
that end-to-end encryption is not standard and, if deemed neces- and LoRaWAN were considered during the early development
sary, must be discussed with the network operator. stages. Sigfox offered connectivity infrastructure, simplifying
system deployment, but neither provided the data throughput
Delivering City-Wide IoT Solutions required. LoRaWAN, at the time, wasn’t secure enough out-of-the-
Concerns regarding security in LPWAN networks influenced box and, without infrastructure partners in the cities where the
technology choices made by DEUS POLLUTRACK Smart City technology was to be deployed, it would be necessary to deploy
GmbH i.G. for their IoT platform [16]. Their team has been devel- gateways that connected to the back-end via cellular networks.
oping IoT sensor networks to monitor particulate matter in cities As a result, 4G and, later, 5G cellular were selected, resolving the
for more than a decade. With the technology deployed in more issues of coverage, reliability, and security to the levels required.
than 15 European cities, it enables local leaders of municipalities  
to make informed environmental decisions regarding air pollu- Nodorft also tells us that, while there are plenty of cheap electronic
tion. Their patented optical particle counters (OPC) are capable solutions for IoT available, these are not robust enough for
of monitoring down to the ultrafine particle (UFP) classification long-term deployment in the environments where their products
(under 0.1 μm). While larger particulates, such as PM10 are consid- are installed. Hence the choice was made to develop according to
ered dangerous for the lungs, UFPs can enter the bloodstream industrial standards, another consideration for those planning
and pass to other organs through inhaled air. their own IoT products.
   
DEUS’s sensor technology (Figure 5) uses a combination of Another aspect is the back-end operations, which they have
stationary and mobile sensors, networked to back-end dashboards developed specifically to the needs of their IoT implemen-
that visualize the data collected. Cities such as Marseille and Paris tation (Figure 6). Moving forward, there is a need to support
use 40 stationary sensors complemented by 300 mobile sensors open-source reporting dashboards to allow government bodies
[17]. Mobile sensors are fitted to vehicles of partners, such as using the system and citizens to access the data, which requires

58 May & June 2022 www.elektormagazine.com


ELEKTOR INDUSTRY

a cloud services provider. And, while there are plenty of choices, relationships if they go it alone. Without a doubt, expertise, either
the provider is considered as important as the technical solution. hired or loaned, is essential to move beyond example applications,
Thus, the search is on for a provider that can provide personal demonstration dashboards, and test IoT services. Finally, it is vital
support and not just an impersonal customer service chatbot. to fix your vision while remaining agile in all areas of implemen-
  tation, from technology choices to target market, to fulfill it.
With so much experience in significant IoT deployments and   220053-01
learning much about the technical challenges, I wondered what
other advice Nodorft could offer those seeking to implement IoT
solutions. “We’ve always stayed true to our vision,” he replies, Contributors
“which has often required us to change the approach.” This has Text: Stuart Cording
meant evaluating different technologies, working with different Editors: Jens Nickel, C. J. Abate
partners, and modifying the sales strategy on their road to success. Layout: Harmen Heida

Teams of Experts and Partnerships Required


Looking at the available IoT landscape, it is clear that business
opportunities abound, regardless of whether you are focused
on solutions for consumers or industry. However, the journey
from concept to deployment is fraught with challenges. While
embedded systems developers may be well versed in hardware and
firmware development, and may even have experience in wireless Questions or Comments?
technologies, IoT and its security and scalability challenges may Do you have technical questions or comments about this article?
be too much for an organization to tackle alone. Email the author at [email protected] or contact Elektor
  at [email protected].
According to the European Commission’s report, large organiza-
tions also have the upper hand in business relationships when
it comes to services and platforms. Small players and startups
will struggle to get the support they need in these asymmetrical

WEB LINKS
[1] Elektor IoT Articles: www.elektormagazine.com/select/internet-of-things-IoT
[2] “IoT Insights, Edition 3,” Microsoft/Hypothesis, October 2021: https://bit.ly/3rxMk3a
[3] “The Journey to IoT Value,” Cisco, May 2017: https://bit.ly/3GzdJWS
[4] Dr. J. Lasquety-Reyes, “Smart Home - revenue forecast in Europe from 2017 to 2025,” Statista, June 2021: https://bit.ly/3LlGiuG
[5] “Sector inquiry into the Consumer Internet of Things,” European Commission, January 2022: https://bit.ly/3Lgw9iE
[6] “Final report - sector inquiry into consumer Internet of Things,” European Commission, January 2022: https://bit.ly/3B2Htu9
[7] “The best voice assistant,” ZDNet, September 2021: https://zd.net/3rxf6Rt
[8] L . Tan, “Comparison of LoRa and NBIoT in Terms of Power Consumption,” KTH Royal Institute of Technology, January 2020:
https://bit.ly/3JafsUb
[9] S
 . Dudek, “Low Powered and High Risk: Possible Attacks on LoRaWAN Devices,” Trend Micro, January 2021:
https://bit.ly/3rA02Tg
[10] S. Dudek, “Gauging LoRaWAN Communication Security with LoraPWN,” Trend Micro, February 2021: https://bit.ly/3LhV0T5
[11] S. Dudek, “Protecting LoRaWAN Hardware from Attacks in the Wild,” Trend Micro, March 2021: https://bit.ly/3rxquge
[12] T.C.M. Dönmez, “Security of LoRaWAN v1.1 in Backward Compatibility Scenarios,” Elsevier, 2018: https://bit.ly/3GtzKq0
[13] Microchip Product Page - ATECC608A: https://bit.ly/3B7zIms
[14] F .L. Coman et al., “Security issues in internet of things: Vulnerability analysis of LoRaWAN, sigfox and NB-IoT,” IEEE, June 2019:
https://bit.ly/3uwhUQX
[15] “NB-IoT, LoRaWAN, Sigfox: An up-to-date comparison,” Deutsche Telekom AG, April 2021: https://bit.ly/3uyUydj
[16] DEUS Pollutrack Website: https://bit.ly/3sHL9O5
[17] DEUS Sensor Measurement Network: https://bit.ly/3Gzjbcc

lektor May & June 2022 59


Elektor infographic
By Robert van der Zwan

IoT: Is It the New Holy Grail?


What is IoT? We all know what
IoT stands for. The question 1.900
≈1.855
should rather be: what should 1.800 Different Outlooks on global IoT Market Size (USD Billion)
count as the Internet of 1.700
Things? Does the IoT market
1.600
include Data Warehouse as
1.500
a Service (DwaaS)? Does IoT
include cybersecurity? Or do 1.400 ≈1.385
such sectors stand on their 1.300 ≈1.300
own? Apart from the debate 1.200
on inclusion and exclusion, e
enc
it remains surprising how
1,100
Int ellig
Mordor ts
igh
1.000
different the outlooks on the h
ns rc
global IoT market size can be. 900 ssI s ea
s ine C Re
The outlooks (yes, plural) of 800 Bu BC
e
market research companies 700 ≈760 rt un
are so different that the glass Fo
is not only half full or half
600 ≈565
Markets
empty, but also completely 500 Marketsand
full to the point of overflowing. 400
There must be something 300 ≈380
close to a Holy Grail here. 200

(Sources: BCC Research, 100


Fortune Business Insights,
MarketsandMarkets, Mordor 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
Intelligence)

Three Ingredients? No, There Are Four


When one thinks of IoT, one thinks of devices and their
Device Management
connections to a central computer. But such a simple
Cloud Platform view is no longer in line with reality. Apart from a
Network Management device, a connection and a computer, there is another
ingredient: a cloud platform, enabled by data centers.
Devices send their information to the cloud, where it
is stored and analyzed. A computer of the customer
taps into the cloud to get the final results. This Data
Warehouse as a Service (DWaaS) or Platform as a
Service (PaaS) represents about 20% of global IoT
revenue. Cloud platform services are expected to grow
round 22% between 2021 and 2026.

Global IoT Market Share, by Component, 2020 (Source: BCC Publishing, Fortune Business Insights)

60 May & June 2022 www.elektormagazine.com


1106

200

Negative Effect 906

Covid-19 Grows Over the Years


Vodafone does not want to stand in the way of IoT
companies painting a rosy picture of their market
expectations. However, the telecom company did some
research on the effect of Covid-19 on the global IoT market. 419
38
The multinational concluded that the effects of Covid-19 will
be felt for quite some time. Whereas last year the global IoT 381
market lost 9% of its turnover because of the pandemic, this
percentage will double to 18% by 2025. Although Vodafone
is mindful of the shadow that Covid-19 casts over the
coming years, its report on IoT makes equally clear that the 2021 2025
-9% -18%
sun prevails during that very same period.
Effect of Covid-19 on
(Sources: Saft Batteries, Vodafone) Global IoT Market Size

Where Do All Those


Contribution Industrial Sector
to Total of IoT connections IoT Connections Go?
Which sectors in society will benefit the most from IoT?
When one would have asked that question a couple of
years ago, the answer would have been: the consumers.
Smart home appliances still are very important considering
that anno 2022 the average household in North America
includes no less than nine IoT devices, ranging from
INDUSTRY a frontdoor camera to temperature control. However,
Manufacturing industrial applications (including retail and agriculture)
Retail
will account for 70% of all IoT connections in 2024.
Agriculture
70% The remaining 30% can be divided between consumer
electronics and public services like smart parking, smart
2024 waste, smart street lighting and smart traffic management.

(Sources: Saft Batteries, Global Information, Inc.)

Key Benefits of IoT Deployments


Why Does IoT Make
50%
Everybody’s Heart Tick?
Employee productivity
One thing is very clear: IoT will increasingly become a part of our daily
lives. But why? Is it because IoT devices are becoming cheaper by the
42%
day? This may be true but of course begs the question why vendors
can rely on a mass market and lower their prices so much. The answer Asset uptime
(consistency and reliability)
is basically twofold: (1) the IoT saves money in substantial amounts
for its users and (2) it will create new revenue streams, also to a very 34%
large degree. When it comes to savings, one can think of an increase in
employee productivity and asset uptime. Creating new revenue streams Have seen IoT directly generate
new revenue stream
or enlarging existing ones is another way of earning money. How about
checking if your houseboat is OK while on holiday? 34%
(Sources: Saft Batteries, Vodafone) Have seen existing revenue streams
increase by an average of 24%

lektor May & June 2022 61


background

Preferably Wired
After All
Tips for Developing
a 1 Gbit/s Interface
in an Industrial
Environment

By Dr. Heinz Zenkner (Freelance Industrial wireless sensor networks can to receive the station’s signal. In addition,
Consultant at Würth Elektronik) be established using smart sensors and there is a possibility that the network
meters that use efficient modulation and could be accessed from the outside or that
Wireless networks are coding techniques with good propaga- the wireless signal transmission could be
becoming increasingly tion characteristics and low bandwidths. interfered with.
popular, especially in However, the majority of the use cases  
explored are limited to low throughput As a result, wireless data transmission is
industrial applications. applications. For these use cases the actual intrinsically less reliable than transfers
However, there is a strong throughput is often no more than 1 Mbit/s. through a wired network. Thus, particu-
case for robust cabling via   larly in industrial settings, there may be
There are no definitive boundaries in instances where a wired Ethernet network
Ethernet in many cases a wireless network. For example, even is the only viable solution.
as the more reliable and minor adjustments to the access point’s
secure option. This article antenna positioning can have a significant Wired Ethernet Network
effect on the signal strength at the other Similar to wireless networks, wired
demonstrates how to stations. The signal is attenuated by walls, networks work by exchanging Ethernet
easily implement a 1 Gbit/s ceilings, and floors, and reflected by metal- frames between endpoints. There are
interface. lic objects. While a station may be able to a few rules to follow when setting up a
receive the signal from an access point, network to avoid problems. The most
  the access point in turn may not be able common cause of network problems is

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


rule breaches. For example, in Ethernet, a bandwidth of 62.5 MHz per channel former) is the device-to-Ethernet cable
wire length must not be arbitrary. When (2 bits per symbol). The signal voltage at interface. The transformer provides the
cascading, i.e., connecting hubs in series, 1000BASE-T (GB Ethernet) is typically necessary galvanic isolation between the
an arbitrary number of hubs is not permit- 750 mV differential, for the limits 820 mV device and the cable while at the same
ted, and an unfavorable network configu- > VSignal > 670 mV at a load of 100 Ω. time matching the impedance of internal
ration can also lead to errors or add unnec- logic and the balanced wire pairs. Further-
essary loads on the network. However, 1 Gbit/s Ethernet Front-End more, the transformer protects the device
depending on the cable quality and the A typical front-end for Ethernet is from transient interference and suppresses
performance of the hardware, the expected equipped with an RJ45 port. These are common mode signals between the trans-
data rates are often not achievable. intended for full-duplex transmissions, ceiver IC and the cable, both within the
  i.e. simultaneous transmission of send device and between the external cable
Currently, 100Base-TX (100 Mbit/s Fast and receive data. This is possible because and the device’s electronics. However, the
Ethernet), Gigabit Ethernet (1 Gbit/s), the connector contains two pairs of wires, device must also be capable of transmit-
10 Gigabit Ethernet (10 Gbit/s) and 100 one in each direction (differential voltage ting data at a rate of up to 1 Gbit/s without
Gigabit Ethernet (100 Gbit/s) are available. principle). The IEEE standard specifies significantly degrading the transmit and
For most applications, Gigabit Ethernet galvanic separation via a transformer for receive signals. Additional components
works well with regular Ethernet cables, each RJ45 connection. This transformer are needed to meet the matching and
specifically CAT5e and CAT6 cabling protects the devices from damage caused electromagnetic compatibility (EMC)
standards. These cable types adhere to the by the line’s high voltage and prevents criteria.
1000BASE-T wiring standard, alternatively voltage offsets caused by potential varia-  
referred to as IEEE 802.3ab. tions between the devices. The circuit Figure  2 depicts a circuit diagram of
  diagram for a Gigabit Ethernet interface the Gigabit Ethernet interface using
The 1 GB Ethernet interface conforms is shown in Figure 1. discrete components. The LAN trans-
to the 802.3ab-1999 (CL40) standard former provides DC isolation between
and requires four wire pairs/channels Discrete Circuitry of the the electronics and the network cable. The
for signal transmission. This results in a Gigabit Ethernet Interface primary-side winding’s middle tap depicts
symbol rate of 125 Megabaud (MBd) and The Ethernet transformer (LAN trans- the so-called “Bob Smith” termination.

Figure 1: Basic circuit of a Gigabit Ethernet interface. Representation of a transmission channel with a total of four channels.
(Source: Würth Elektronik)

Partner Content lektor May & June 2022 63


Here, one 75-Ω resistor is connected to
each wire pair to form a “star point”, which
is then galvanically isolated and connected
to the housing ground via two parallel
100-pF/2-kV capacitors. The additional
common-mode chokes integrated in
module X3 mitigate interference that is
coupled both capacitively and inductively
via the long Ethernet cables and could
potentially impair Ethernet data commu-
nication as common-mode interference.
 
In Figure 2, R9, R10 and C52 are used
to power the LEDs that are typically
integrated in the connector socket.
Through the capacitors C36 to C38 and
C41 to C43, the shielding of the Ether-
net socket can be connected to the board
ground (GND). For sheet metal housings,
it makes sense to omit these capacitors
and connect the electronics’ ground (GND)
directly to the housing via screw connec-
tions. For plastic housings the capacitors
should be fitted to connect the shield of
the Ethernet cable to the reference ground.
The 0-Ω resistors R19 and R20 have the
same purpose. However, unlike with capac-
itors, there is no galvanic separation here.
Alternative configurations were included
in this section for “experimental” purposes
to compare the shielding quality of various
Ethernet cables. The capacitors C32 to C35
on the secondary side of the transformers
connect the center taps of these in an RF
manner to ground (GND). Galvanic isola-
tion via capacitors is essential to eliminate
DC equalization currents from the PHY.
The resistors R27 to R30 are included to
comply with some PHY manufacturers
requirements (Current Mode Line Driver
- Option) but are typically not needed if
the PHY operates in “Standard Voltage
Mode”. However, the TVS diode arrays
D6 and D7 are indispensable because
they isolate transient interferences on the
interface side of the PHY from the circuit
ground (GND). On the secondary side, i.e.
after the transformers of the X3 module,
transient disturbances occur in common
mode, and therefore a TVS diode must be
connected to each terminal of the trans-
formers against the reference ground.
The secondary side of the transformer,
Figure 2: A Gigabit Ethernet interface’s discrete circuit. Module X3 contains the LAN
transformers and common-mode chokes necessary to prevent interference.

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


however, has lower interference levels than
the primary side.  Important for the TVS
diodes to function properly is a low-im-
pedance connection of the diodes, on the
one hand looped into the signal lines and
on the other hand to ground.
 
Figure 3 illustrates the layout of all four
layers of the board starting with the Ether-
net interface area. The package/socket
ground is isolated from the electronics
GND in all four layers. Thus, the package
ground’s surfaces do not overlap with those
of other layers to keep capacitive coupling
as low as possible. The ground planes
were plated through every 4 mm in a grid
pattern. The Ethernet socket’s signal lines
are balanced, with a differential impedance
of 100 Ω routed to the reference ground.
The conductor pairs have a track width
of 0.154 mm and are spaced 0.125 mm
apart. The Ethernet socket is positioned
on the PCB’s edge to ensure a low-imped-
ance connection to a metal enclosure if
necessary.
 
The transformer module (X3) is placed
nearby to minimize the effects of electri-
cal coupling, or interference from long
traces. As with the primary side, the
secondary side of the transformer module Figure 3: The layout of all four board layers of the Ethernet interface area.
must maintain a differential impedance
of 100 Ω to the reference ground for the
conductor paths. To avoid voltage drop ble circuit and layout design, a system-de- requirements can be developed. Further
due to parasitic inductance, the TVS arrays pendent ground concept, and the right information on these topics, as well as
must be connected directly into the signal choice of components. Only when all these on other interface standards, is available
path and to GND. factors are taken into account a product in various app notes published by Würth
that functions reliably and meets stringent Elektronik at [1].
EMC Compliance 220182-01
In terms of electromagnetic compatibility
(EMC), the board complies with industry About the Author
standards for immunity (EN61000-6-2) Dr.-Ing. Heinz Zenkner is a freelance consultant at Würth Elektronik in
and EN55032 Class B radio interference the areas of technical marketing and application engineering as well
emission levels for multimedia equip- as a lecturer at the technical academy in the area of EMC. At the same
ment. Numerous factors must be consid- time, Heinz is a publicly appointed and sworn EMC expert. He has
ered when designing a 1 Gbit/s Ethernet authored numerous technical journals and books, and has worked as
interface. These include an RF-compati- a lecturer at various universities, the IHK and at numerous seminars.

WEB LINKS
[1] Würth Elektronik Application Guide: https://www.we-online.com/applicationguide/en

Partner Content lektor May & June 2022 65


background

Bringing Real-Time
Object Detection
to MCUs with Edge Impulse FOMO

By Jan Jongboom, Edge Impulse

We humans rely heavily on sight to perform Say Hello to FOMO


many daily tasks, from some of the most basic We’re making it a reality. We developed
a novel neural network architecture for
to the most complex. With one look, we know if object detection called Faster Objects, More
there are people in the room with us, if there’s Objects, or FOMO (Figure 1). It’s designed
an elephant nearby, or how many free parking from the ground up to run in real-time on
microcontrollers, so embedded engineers
spaces are available. Despite the importance of can (ahem) avoid the fear of missing out
vision, though, many embedded devices still when it comes to computer vision.
can’t perceive things visually. Wouldn’t it be
Fast, Lean & Flexible
amazing if we could teach all our devices to see FOMO is capable of running on a 32-bit MCU,
the world the way we do? like an Arm Cortex-M7, with a frame rate of
30 frames per second. And the next time you
  choose a Raspberry Pi 4 type device, you’ll be
In recent years, there have been some Imagine if we could add even more able to do object detection at a rate of about
amazing developments in computer advanced vision capabilities to every 60 frames a second. That’s roughly 30 times
vision, fueling progress in things like embedded device! faster than MobileNet SSD or YOLOv5.
self-driving cars and biometric immigra-
tion gates (very useful if, like me, you travel
a lot!). But these use cases are incredibly
computationally expensive, requiring
costly GPUs or special accelerators to run.
 
The awesome thing is that not all comput-
er-vision tasks require such intensive
compute. Any yes/no question (“Do I
see an elephant?,” “Is this label properly
attached to the bottle?”) can add tremen-
dous value to constrained embedded
devices. What’s more, these problems of Figure 1: FOMO classification within Edge
image classification can even be solved by Impulse Studio.
today’s microcontrollers.

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


Figure 2: Run object detection on a wide variety of dev boards, including Figure 3: Here’s a former iteration of the FOMO approach used to count
the Arduino Portenta. individual bees.

 
FOMO scales down to about 100 kilobytes small objects very effectively (Figure 3). had to deal with when it came to computer
in RAM, making it possible to run object That’s something that MobileNet SSD and vision (Figure 4).
detection in real-time on everything YOLOv5, despite being larger and more  
from highly-constrained Arm Cortex-M4 capable models, can’t do very well. To learn more about FOMO and exper-
cores to more powerful ones, like the iment with your own algorithm, visit
Cortex-M7 cores on the Arduino Portenta No More Missing Out edgeimpulse.com/fomo.
H7 (Figure 2), the new Arduino Nicla Vision FOMO is available today, runs on a wide 220207-01
(another dual Arm Cortex-M7/M4 CPU), or variety of computing platforms, and is
even specialized DSPs such as the Himax compatible with Linux systems, Cortex-M
WE-I. microcontrollers, and specialized DSPs. About the Author
  Add a camera and Edge Impulse, and you’re Jan Jongboom is an
FOMO can scale from the tiniest micro- all set. embedded engineer
controllers all the way to full gateways or   and machine
GPUs. This high degree of flexibility also With FOMO, you can quickly add object learning advocate,
makes FOMO useful when fault detection detection to just about any camera-based always looking for
requires identifying variations that are very, device, and avoid the fear of missing out ways to gather more
very small within an image. that, until now, embedded engineers have intelligence from the real
  world. He has shipped devices, worked
In an MCU with strictly limited compute on the latest network tech, simulated
and memory capacity, it’s best to use an microcontrollers and there’s even a
image size of about 96x96 pixels. But with monument in San Francisco with his
a larger microcontroller device, 160x160 name on it. Currently he serves as the
pixels is probably fine. The important cofounder and CTO of Edge Impulse,
thing is that FOMO is fully convolutional, the leading development platform
so it works on any arbitrary input size. If for embedded machine learning with
you need higher granularity, more detail, 80,000+ projects.
or more objects, you can just scale up the
input resolution.

It Sees the Little Stuff


As long as the objects in the frame are of Figure 4: Training on the centroids of beer
similar size and don’t overlap, this new archi- bottles. On top the source labels, at the bottom
tecture can even spot and count lots of very the inference result.

Partner Content lektor May & June 2022 67


background

ELECTRODES PERMANENT OUTPUT


MAGNETS ANTENNA
DRIFT INPUT
CATHODE

Traveling
HEATER TUBE ANTENNA HELIX ATTENUATOR COLLECTOR

N S

Wave
N S
INPUT OUTPUT
1 2 WINDOW WINDOW

Tubes
TO HEATER TO ELECTRODE TO HELIX TO R-F TO R-F TO COLLECTOR
CATHODE VOLTAGES VOLTAGE INPUT OUTPUT VOLTAGE
VOLTAGE

Figure 1: Basic design of a traveling-wave tube.

Peculiar Parts,
the Series
Since the streaming electrons travel much tions, a small group of enthusiasts still like
By Neil Gruending
more slowly than the RF electrons, the RF experimenting with these wonderful little
The world of RF amplifiers signal is fed through a spiral wound wire, amplifiers in amateur microwave transmit-
called the helix. This slows the RF signal ters [3]. Their biggest challenge, however,
is fascinating because of down to match that of the electron stream. is finding the tubes!
the wide range of methods   210418-01

in use. Today, many are As the RF electrons proceed down the helix,
they modulate the velocity of the electrons Questions or Comments?
constructed from solid- in the stream because the in-phase Do you have technical questions or
state components, but there electrons speed up, and the out-of-phase comments about this article? Email Elektor
are still situations where electrons slow down. These modulated at [email protected].
electrons then bunch together, inducing
vacuum tubes are the only an amplified signal back into the helix that
suitable choice. We’ve is then picked off the end of the helix using
looked at klystrons in the a directional coupler.
 
past, so, this time, let’s look When compared to klystrons [1], travel-
at the traveling-wave tube ing-wave tubes have the advantage of
amplifier, another unsung wider bandwidths. Additionally, they don’t
require resonant components, making
electronic hero. them ideal for lower power microwave
  applications like radar or even spacecraft Figure 2: Collins Radio S-Band traveling-wave
and satellites. A great example is the tube amplifier used for communication with
One of the most fascinating things about Collins Radio S-Band amplifier (Figure 2 earth during the Apollo mission.
(Source: Ken Shirriff)
traveling-wave tube amplifiers is how they and Figure 3) used in the Apollo space
work. They feature a heater, cathode, and program [2]. It was a compact, 32-pound,
acceleration electrodes to form an electron 20-W amplifier that transmitted all of the
gun, much like a cathode-ray tube, that voice, data, and television back to NASA’s
beams a stream of electrons to the collec- network of 26-m, earth-based dish anten-
tor (Figure 1). This stream is focused by an nas. By comparison, the ground station
external magnetic field that is usually made used a focused 10,000-W signal to commu-
of permanent magnets. Using velocity nicate back to the craft.
modulation, which mixes the electron   Figure 3: Operating at several thousand volts,
stream with the incoming RF electrons, the Even though traveling-wave tubes are the Collins Radio amplifier was a tightly-packed
tube amplifies the applied RF input signal. mostly the domain of commercial applica- tangle of coaxial cables. (Source: Ken Shirriff)
 

WEB LINKS
[1] N. Gruending, “Klystrons, Weird Component # 12,” Elektor 3/2015: https://bit.ly/2UW4k9G
[2] K. Shirriff, “Inside a 20-Watt Traveling-Wave Tube Amplifier from Apollo,” Ken Shirriff’s Blog, July 2021: https://bit.ly/3ea8lOn
[3] H. Griffiths, “Travelling Wave Tube Amplifiers,” The National Valve Museum, September 1980: https://bit.ly/3wA8aCn

68 May & June 2022 www.elektormagazine.com


background

Narrowband
Internet of Things
Standards, Coverage,
Agreements and
Modules

By Tam Hanna (Slovakia)

Curious about Narrowband


Internet of Things (NB-IoT)?
Is it for you? Let’s take a look. 
source: shutterstock.com

 
Along with LoRa and Sigfox, mobile communication networks LTE-M is basically a ‘light’ version of LTE (4G) with a bandwidth
are also a good option for the transmission of IoT sensor data. The of 1.4 MHz, while NB-IoT is a dedicated wireless communication
upgrade from EDGE to UMTS made this option even more attrac- standard for the Internet of Things. The key difference is that LTE-M
tive, since using a faster transmission system can in the end be additionally supports voice transmission with VoLTE, while an
better than using a lower-power but slower system. However, the NB-IoT system exclusively transmits data messages.
immense bandwidth and power hunger of 4G/LTE make this rule  
of thumb a bit less relevant. The power consumption of the trans- The NB-IoT channels, each with a width of only 180 kHz, use a
mitters is significantly higher, and on top of that the modules are subset of the methods implemented in the full version of LTE.
more expensive. Nevertheless, it can be worthwhile. Uplink uses a simple version of the frequency division multiple
  access (FDMA) method, while downlink uses orthogonal FDMA
In the framework of the specification 3GPP Release 13, desig- (OFDMA). The quadrature phase shift keying (QPSK) modulation
nated by LTE as ‘informational’, the GSM Association defines method does not require especially complex hardware in terms
two systems for the Internet of Things. The first is Narrowband of processing power.
Internet of Things (NB-IoT), and the second is LTE-M, also known  
as LTE Cat-M1 or eMTC. However, it should be noted that introducing NB-IoT usually incurs

lektor May & June 2022 69


Table 1: Frequency bands. Verizon, the natural question here is which bands are used. Band 13,
which is only important for North America, has caused problems
Region Bands
for many Asian or European module providers. Table 1 is taken
Europe 3, 8, 20
from the Deployment Guide [3] of the GSM Association. You should
(Former) CIS countries 3, 8, 20 make sure that the module you choose supports all the bands that
North America 2, 4, 5, 12, 66, 71, 26 are used by your preferred carrier.
Asia Pacific (APAC) 1, 3, 5, 8, 18, 20, 26, 28
Sub-Saharan Africa 3, 8
Availability and Agreements
It goes without saying that wireless communication standards are
Middle East and parts of North America 8,20
only worthwhile if they are also available in practice. In the case of
Latin America 2, 3, 5, 29 the two IoT wireless communication standards, you should have a
look at the interactive world map of the GSM Association in Figure 1
[3] (status as of September 2021). As you can see, Mexico is the only
country where only CAT-M is available (probably because of the larger
additional costs for the carrier for the new hardware. Due to the range), while “NB-IoT only” is more widely available in the rural areas
extremely narrow bandwidth, NB-IoT can easily fit into the guard of Asian countries and, remarkably enough, in Eastern Europe. In
band surrounding the LTE frequency packets. On the other hand, the highly industrialised regions of Europe, North America, Asia,
using NB-IoT in stand-alone mode is of course also possible. Australia and Oceania, both versions are available.
 
Looking at Performance CAT-M agreements are generally ordinary agreements in which
Even the technically most attractive wireless communication the total usage volume and the number of SIM cards determine the
standard is of no use if the transmission capability is insufficient for overall cost. For the sake of completeness, it should be noted that
the intended task. In the case of NB-IoT, the version is an important with regard to cost, an IoT provider such as PodGroup is often a
consideration because there are differences between LTE Cat NB1 better choice than a prepaid SIM card purchased on the open market.
(Release 13) and LTE Cat NB2 (Release 14). The older version can  
only achieve 26 kbit/s in upstream, but Cat NB2 is significantly The claim that NB-IoT is not subject to duty cycle restrictions is
faster with 127 kbit/s upstream and 159 kbit/s downstream. For not borne out by the author’s practical experience as a consultant.
comparison, conventional (not HSDPA) 3G initially achieved Talking with your mobile provider about IoT connectivity is and
380 kbit/s. LTE Cat M1 currently runs at around 1 Mbit/s upstream will remain a matter of negotiation, and all too often limits on
and downstream, and Release 14 raises this to 4 Mbit/s upstream the number of packets in a given time interval will be imposed.
and 7 Mbit/s downstream. Operators rarely publish their exact conditions in this regard, which
  makes the following statement from T-Mobile USA all the more
The differences in latency times are enormous. LTE-M can usually remarkable:
achieve 15 ms, while with NB-IoT the recommended ‘working range’  
is from 1.6 s to as much as 10 s. The module manufacturer Sierra “Join the first nationwide NB-IoT network to power asset tracking,
Wireless, especially popular in the USA, describes the situation connected cities, and more. Limited time offer; subject to change.
as follows: Taxes and fees may be additional. Plan includes 10 single-packet
  transactions per hour at up to 64 Kbps, up to 12 MB. Full service
“Another important fact to consider is that there are no NB-IoT payment due at activation.”[4]
use cases that LTE-M can’t also support. In other words, LTE-M  
supports any LPWA application, whereas NB-IoT is designed for Interestingly, this is only an individual opinion, and Hutchison
simpler static sensor type applications.”[1] Holding Ltd has confirmed that the total volume of data traffic
  (within the bounds of the agreed amount) can be used up in one
In addition, only version 2 of the NB-IoT standard supports position day. Tom Tesch, the Austrian spokesperson of Hutchinson, says
data provision by the network operator. If the module does not have in this regard:
GPS capability or you want to do without an external antenna, you  
can use this approach to obtain basic position data. Release 14 also “The data rate of NB-IoT — in accordance with the standard — is
accelerates searching for new cells, which is mainly beneficial for very low and primarily suitable for the transmission of individ-
moving devices. Despite these new benefits of Cat NB2, LTE-M is ual measurements or status values. For this reason, more than 5
still the best choice for automotive and other mobile applications to 10 MB per month is very rarely needed for NB-IoT devices. For
because it provides smarter cell handover. The final improvement more bandwidth-intensive applications, such as the transmis-
concerns transmit power: Super Low Power transmitters [2], which sion of photos or videos, 3G/4G and of course 5G are more suitable
can operate with only 14 dBm, are only allowed in Release 14. technologies. There are currently no limits on when the volume
  can or may be used, which means that the entire volume can also
If at some point in time you got your hands on a 4G module for be used up in one day.”

70 May & June 2022 www.elektormagazine.com


Figure 1: Comparison of geographic
coverage of CAT-M only (red) and
NB-IoT only (blue) [3].

How to Get Started development environment. This means that our offering is currently
After these basic considerations, it’s time to start thinking about exclusively oriented to business customers, for which we create a
how you can integrate NB-IoT into practical systems. Of course, tailored offer in the course of a consultation process.”
development of customer-specific modems is not feasible for most  
companies, but in the past we have described the ‘design in’ process When working with ‘ordinary’ 2G/3G/4G systems, one way to get
for wireless modules in detail, for example in Elektor 5-6/2021 [5]. around this is to use a ‘virtual’ mobile communication provider such
  as PodGroup. When asked about this, they answered that NB-IoT
If you don’t want to start developing your own board right away, one is currently not really suitable, especially for ‘global’ solutions that
option is to use a ‘turnkey’ evaluation board — although the avail- need to work with a single SIM card.
ability of Qualcomm ICs is proving to be a problem in this regard.  
  There are two reasons for this. Firstly, that the NB-IoT rollout is
Two possibilities are the NBIOT-BG96-SHIELD from Avnet, still relatively limited. And secondly, that roaming agreements
which integrates a Quectel BG96 module, and the 5G NB IoT between the different network operators have generally not yet
click board from MikroElektronika, which hosts a Cinterion been adapted to the new NB-IoT wireless communication standard.
module. Arduino also offers a small development board in the Liked tax treaties between countries, it takes a long time to achieve
form of the MKR NB 1500. However, both of these boards cost such adaptations. In short: international NB-IoT roaming is still
more than 50 dollars. in its infancy.
 
In many cases, it is no longer permitted to supply evaluation board Is It Worthwhile?
equipped with SIMs, so a massive rollout of applications based on Searching for a practical module that supports only NB-IoT is
NB-IoT is far from easy. The reason for this is that network opera- certainly a very tricky endeavour. Quectel, for example, offers
tors have not yet packaged the technology for end users. This is two versions even with the smallest series (BC660): one with only
also openly admitted by operators, as illustrated by the following NB-IoT, and the other with both eMTC and NB-IoT. Both wireless
statement from Hutchison: standards are also present in larger families, such as the very
  popular BG95 and BG96. Open market prices for these modules
“NB-IoT is a very young and innovative network. As there are hardly can only be found at SOS Electronic: the BC660K-GL costs €7.63 is
any devices available on the market, the target group primarily small quantities, while the version with LTE-M and NB-IoT is not
consists of business customers in the hardware (and software) listed. The price there for the BG96 is €19.

lektor May & June 2022 71


Figure 2: Searching for a pure
CAT-M module doesn’t turn
up many results [6].

 
A search for u-blox [6] yields more results. The SARA-N3 family
includes a module exclusively intended for the NB-IoT set of proto-
cols, but the Swiss company does not offer a pure CAT-M device
(see Figure 2).
 
At Gemalto, whose takeover by Thales has made the website even
more confusing than it used to be, there is a pure CAT-M module in
the form of the EMS31, along with a pure NB-IoT module (ENS22)
with the same form factor. At the Czech distributor Sectron you
can compare prices: the EMS31 costs €14, the ENS22 only €8.
 
Information on current consumption (in roundabout form) can be
found in the data sheets, which go by the name ‘Hardware Interface
Description’. The highest current consumption of the EMS31 occurs
when operating in Band 4 and is 239 mA with a supply voltage of
3.8 V. For the ENS22, the highest current listed is 404 mA in Band 28,
but it should also be noted that wireless modules often require
Figure 3: A traditional Stierian windmill serving as a scarecrow. (Source:
Martin Geisler, CC BY-SA 4.0 [7]). peak currents like this only for a very short time.

WEB LINKS
[1] LTE-M vs. NB-IoT: What are the Differences?: https://www.sierrawireless.com/iot-blog/lte-m-vs-nb-iot/
[2] Wikipedia entry on narrowband IoT: https://en.wikipedia.org/wiki/Narrowband_IoT
[3] GSMA: Word map of IoT wireless communication standards: https://www.gsma.com/iot/deployment-map/
[4] T-Mobile Narrowband IoT web page: https://t-mo.co/3EC5Jo4
[5] Tom Hanna, “Do Not Fear the Cellular Module!,” Elektor Mag 5-6/2021:
https://www.elektormagazine.com/magazine/elektor-175/59527
[6] u-blox mobile communication modules: https://www.u-blox.com/en/cellular-modules
[7] Klapotetz: https://bit.ly/3nOr0Fb

72 May & June 2022 www.elektormagazine.com


What’s In It for You? Questions or Comments?
From a technical point of view, NB-IoT works perfectly, and once you Do you have technical questions or comments about this article?
have arranged an agreement with a carrier, the effort for network If so, please contact the author at [email protected] or
operation is limited to a phone call to your lawyer, unlike the situa- the Elektor editorial staff at [email protected].
tion with a home LoRa WAN. The relatively low peak and quies-
cent current consumption of the modules also helps to keep your
electricity bill within bounds. Contributors
  Text: Tam Hanna
Whether or not it’s worthwhile in the end is primarily a matter of Editor: Rolf Gerstendorf
scale, just like tax havens such as Dubai or Monaco. If you buy five Translation: Kenneth Cox
modems in a year, operate with a ‘full’ 4G module or, even better, a Layout: Giel Dols
module with a beefier power adapter and costing a few euros more,
the sad experience of the author is that in practice you will repeat-
edly need the ‘other’ wireless standard, if only because some base
stations do not support every wireless communication standard.
  RELATED PRODUCTS
Naturally, the situation looks different if you are purchasing 50,000
modems that will all go to the same customer. If the mayor’s office
of Großdorf am Klapotetz (Figure 3) needs NB-IoT, the local carrier > H. Henrik Skovgaard, IoT Home Hacks with ESP8266
will probably upgrade their network, and the cost savings from the (Elektor, 2020, SKU 19159)
large number of devices will also help. www.elektor.com/19159
180021-01

Advertisement

Ensure your products are 100% authentical


Mouser was the first SAE AS6496 accredited distributor

Widest selection of electronic components in stock™


mouser.co.uk/authentic

Authentic products-185x124-en.indd 1 23.03.22 07:52

lektor May & June 2022 73


review

Dragino LPS8
Indoor Gateway Speedy LoRaWAN Gateway Setup

Figure 1:The Dragino LPS8 Indoor


Gateway. (Source: Dragino [5])

By Mathias Claußen (Elektor) LoRaWAN is a topic we have featured many The Dragino LPS8
number times in Elektor. It is relatively easy The Dragino LPS8 Indoor Gateway (Figure 1)
We have often described to build a basic LoRaWAN node which has is housed in a plastic enclosure and could
how you can interconnect an associated sensor or actuator module. In easily be mistaken for a Wi-Fi router. The
your own electronics devices this type of setup, a LoRaWAN module (which electronics inside are powered by a small
handles communication to the network) is Atheros (today Qualcomm) AR9331 Wi-Fi
using a LoRaWAN link. If connected to a microcontroller board such as SoC clocked at 400 MHz which is specifi-
you are not within range an STMicroelectronics STM32 or Raspberry cally designed for use in router platforms and
of an existing LoRaWAN Pi Pico [1, 2], and this provides an interface access points. With 64-MB RAM and 16-MB
to the sensor. In order for the data sent to Flash, its processing power is not spectac-
gateway, or if you simply and from the node via LoRa to be transported ular when compared with something like a
want to delve a bit deeper further, a remote station is required. In this Raspberry Pi Zero 2 W, but it is more than
into the topic, you can set case, a LoRaWAN gateway will accept the enough for the functions that the gateway
data over the air via LoRa and forward it to needs to perform. The SoC also supports
up and operate your own an Internet platform like The Things Network Wi-Fi according to 802.11 b/g/n and provides
gateway. We tried this using (TTN). You can use a pre-existing gateway a 10/100 Mbit LAN port. The communica-
the low-cost Dragino LPS8 that’s already been set up in your area (many tion rates available are more than capable of
are run by volunteers), or you can set up your handling the relatively slow data rate used by
Indoor Gateway. own gateway. I have been using a Dragino LoRaWAN. The gateway itself does not have
  LPS8 to provide an Indoor Gateway for more to provide a lot of computing power either,
than a year now. as it only takes care of the integrated LoRa

74 May & June 2022 www.elektormagazine.com


Figure 2: Block diagram of the Dragino LPS8. (Source: Dragino [6])

transceiver module and forwards the data to


the Internet. A block diagram can be seen
in Figure 2.
 
The LoRa transceiver is a combination of
a Semtech SX1308 LoRa baseband chip
(Figure 3) and two SX1257 front-end modules
(Figure 4). This combination provides the
conversion from the radio interface to Ethernet.
The gateway is powered via its USB type C port Figure 3: Block diagram of the SX1308 baseband chip. (Source: Semtech [7])
and requires a 5 V/2 A (10 W) mains adapter.
 
As the name of the gateway suggests, the
device is not weatherproof and is intended
for use inside a building, so the environment
should be dry and relatively dust-free. The
building structure and internal walls will
reduce the radio coverage compared to an
equivalent device mounted outdoors in free
space with a mast-mounted antenna.

The LPS8 Manual, Firmware


and Setup
The most recent version of the Dragino
manual (available online [3]) describes how
to set up the gateway. The manual has been
continuously maintained since the product
was released and reflects the features and
updates of the current firmware. This is
indeed praiseworthy; I just wish that some
other product manufacturers would adopt
the same attention to detail when it comes
to documentation.
Figure 4: Block diagram of the SX1257 frontend module. (Source: Semtech [8])
 

lektor May & June 2022 75


The firmware itself is also well maintained.
The current release is dated November 4, 2021
(as of December 15, 2021) [4]. It’s advisable to
update to the latest version before the gateway
is put into service. That will ensure any known
bugs or security weaknesses should be ironed
out as far as possible.
 
The manual guides you through the setup.
Figure 5: Communication paths available via the LPS8 gateway.
All you need to do is configure the network
appropriately and make the settings for the
LoRaWAN link (e.g., The Things Network).
From this point, the LoRaWAN gateway is
ready for use (Figure 5). web interface or command line to add more Questions or Comments?
functions to the device. Do you have any technical questions or
An OpenWRT Substructure comments about this article? Contact the
Even though the first page of the web inter- A Reliable Solution author at [email protected]
face doesn’t suggest it, the Linux-based Open I have personally been using a Dragino LPS8 or contact the Elektor team at editor@
Wireless Router  (OpenWRT) firmware is used now for over a year. During that time, it has elektor.com.
as the basis for the Dragino LPS8 indoor proved to be a low-maintenance and reliable
gateway. This not only takes care of the LoRaWAN gateway, which is really all you could
LoRaWAN gateway function, but also provides ask of such a device. It continues to do a good Contributors
a number of other settings for the router (IP job servicing my various LoRaWAN nodes and Text: Mathias Claußen
addresses, forwarding, Wi-Fi). gives excellent coverage throughout the build- Editor: Jens Nickel, C.J. Abate
  ing (and surrounding area). If you are thinking Translator: Martin Cooke
Thanks to the OpenWRT substructure, an LTE of installing an inexpensive LoRaWAN gateway Layout: Harmen Heida
or 5G modem can also be connected to the in a domestic environment, you should take
gateway USB port if no other link to the Inter- a closer look at the Dragino LPS8 Indoor
net is possible at the device’s location. If you Gateway, which is currently available from the
like, you can also access the Linux command Elektor Store [5]. 
line using SSH. (Do so at your own risk!) 210680-01
Additional packages can be installed via the

RELATED PRODUCTS

> Dragino LPS8 Indoor LoRaWAN Gateway (868 MHz) (SKU 19094)
www.elektor.com/19094
 
> Seeed Studio LoRa-E5 STM32WLE5JC Development Kit (SKU 19956)
www.elektor.com/19956
 

WEB LINKS
[1] M. Claußen, “My First LoRaWAN,” ElektorMag 3-4/2020: http://www.elektormagazine.com/magazine/elektor-141/57159
[2] M. Claußen, “LoRa with the Raspberry Pi Pico,” ElektorMag 7-8/2020:
http://www.elektormagazine.com/magazine/elektor-179/59721
[3] Dragino LPS8 Indoor Gateway Handbook: http://www.dragino.com/downloads/index.php?dir=LoRa_Gateway/LPS8/
[4] Firmware download of Dragino LPS8 Indoor Gateway: https://bit.ly/LPS8-firmware-release
[5] Gateway picture resource: http://www.dragino.com/media/k2/galleries/148/LPS8-10.jpg
[6] Dragino LPS8 Indoor Gateway Manual: https://bit.ly/LPS8-user-manual
[7] The Semtech SX1257 Front-End Data sheet: https://sforce.co/3fZmy1f
[8] The Semtech SX1308 Transceiver Data sheet: https://sforce.co/32zxAqV

76 May & June 2022 www.elektormagazine.com


elektor books

Explore ATtiny Microcontrollers


Using C and Assembly Language
Sample Chapter: ATtiny I/O Ports

By Warwick A. Smith (South Africa)

I/O ports control the pins of a microcontroller


and allow them to be individually configured
as input pins or output pins. That’s such a
broad statement, it should fit just about any
newbie course or introduction to microcontroller
programming. However, to truly comprehend and
exploit a microcontroller’s I/O abilities, you need to delve
deeper into the machine. In this article, Elektor book author
Warwick Smith pulls it off by demo-ing some assembly-code programming on the popular
ATtiny micro. Convincing? Let’s check it out!

Editor’s Note. This article is an excerpt from the 376-page book Explore ATtiny Microcontrollers using C and Assembly Language (W. Smith,
Elektor, 2021) The excerpt was formatted and lightly edited to match Elektor Mag’s editorial standards and page layout. Being an extract from
a larger publication, some terms in this article may refer to discussions elsewhere in the book. The Author and Editor have done their best to
preclude such instances and are happy to help with queries. Contact details are in the Questions or Comments? box.

I/O ports are configured and controlled using a set of four registers Remember that to use this configuration a programmer/debugger,
in the ATtiny13(A) and ATtiny25/45/85. When a pin is configured such as an Atmel-ICE, or AVR Dragon must be used.
as an input pin, a program running on the AVR can read the logic
level on the pin. If a switch is attached to the pin, the logic level
on the pin can be read to see if the switch is open or closed. When
a pin is configured as an output pin, it can be used to switch the
logic level of the pin high (to logic level 1) or low (to logic level 0).
An output pin can be used to drive an LED as was done in the LED
blink project described elsewhere in the book.

Configuring I/O Pins as Outputs in Assembler


In this section, we look at how to configure more than one pin as
an output using an 8-pin ATtiny with five LEDs attached to pins
with series resistors. Code is used to configure the LEDs as a 5-bit
binary counter that counts up from zero.
 
Figure 1 shows a circuit diagram of an ATtiny13(A) or ATtiny25/45/85
AVR microcontroller with five LEDs attached to I/O pins PB0 to PB4.
Pin PB5 of the ATtiny microcontroller in the circuit is used as the
debugWIRE pin for programming and debugging the microcontroller. Figure 1: Five-LED Counter circuit diagram.

lektor May & June 2022 77


only one pin for programming. Another solution is to program the
AVR on another breadboard using ISP/SPI, and then plug it into the
target circuit afterwards.
 
Alternatively, an AVR with more pins can be used, but the free port
pins don’t always match the same pins from the same port of an
8-pin PDIP ATtiny. For example, if using port pins PB0 to PB4 like
the circuit of Figure 1 does, there are not five consecutive free pins
available on the 14-pin ATtiny24/44/84 range of AVRs, because the
ISP/SPI pins use up pins from both port A and port B. On the 20-pin
ATtiny26/261/461/861 range, the whole of port A is free with an
ISP/SPI programmer connected, but this means that the software
needs to be changed to use port A instead of port B. Fortunately,
the 20-pin ATtiny2313/4313 range does have pins PB0 to PB4 free
with an ISP/SPI programmer connected.
Figure 2: Five-LED count circuit breadboard layout.
 
Putting the AVR into debugWIRE Mode
In order for the microcontroller to be programmed using a single
  debugWIRE line as shown in Figure 1, it is necessary to first connect
A program-only USB programmer will not work in debugWIRE mode, all of the ISP header lines to the microcontroller from the USB
and can not perform debugging. Reminder: Do not set the DWEN fuse programmer/debugger and then set the DWEN fuse of the AVR to
with a program-only USB programmer because it will not be able put it into debugWIRE mode. Your AVR will now be in debugWIRE
to take the AVR back out of debugWIRE mode. The idea of using mode. If not, attach your programmer/debugger, such as an Atmel-
debugWIRE mode with this example circuit is to free up the other pins ICE or AVR Dragon, and ensure you are ready and able to set the
of the AVR that are normally used in ISP/SPI programming mode. DWEN fuse. Once the DWEN fuse is programmed, all of the ISP header
  connections can be removed from the circuit except RESET, +5 V
Program-Only Programmers (Vcc) and GND as Figure 1 shows.
USB programmers with program-only capabilities can be used with
the circuit of Figure 1 to load the example program that follows Build the 5-LED ATtiny Circuit on Breadboard
and see the count value displayed on the LEDs. If you have the hardware, then build the circuit of Figure 1 on an
  electronic breadboard. Make sure that the five LEDs are connected
Wire the LEDs as shown in Figure 1 and Figure 2. The original in a row on the breadboard with pins PB0 to PB4 connected in
USBasp design and the original USBtinyISP design both have protec- order starting at PB0 on the right. LED D1 will then be on the
tion resistors on the lines that drive out from these programmers, right of the row and D5 on the left. In other words, we want a
protecting the programmer, and the target AVR chip. The Arduino single row of LEDs with PB0 connected to the LED on the right,
Uno programmed as an ArduinoISP does not have any protection PB1 connected to the LED next to it on the left, PB2 connected
resistors, but these can be added on the Arduino Uno MOSI line to the LED third from the right, and so on, as can be seen in the
and SCK line which drive into the target AVR. 270-Ω protection breadboard layout of Figure 2. The image shows just the outlines
resistors are used in the original USBasp design, and are placed on of the LEDs so that they do not block the view of the wire connec-
the MOSI, SCK and RESET lines. 1k5 resistors are used on the MOSI tions and resistors. If you do not have the hardware, then follow
and RESET lines of the original USBtinyISP design. the programs using a simulator.
 
Protection resistors prevent a short-circuit should one of the target Assembly Code for the 5-LED Count Circuit
AVR pins drive an output voltage at the same time that the program- Start a new Microchip Studio AVR Assembler Project called led_
mer drives an output voltage of opposite polarity. count_asm. Type the code shown in Listing 1 into main.asm of the
  project, replacing the skeleton code.
Peripheral Hardware Devices Interfering with Programming  
Although the circuit of Figure 1 can be programmed using the ISP/SPI If you are using the hardware of Figure 1, then select the hardware
interface with the LEDs and series resistors attached, other circuits tool (your debugger), such as the Atmel-ICE within Microchip Studio,
may have hardware attached that interferes with programming. If any with debugWIRE as the interface. You do so by clicking the hammer
peripheral hardware attached to pins of an AVR to be programmed icon on the second top toolbar. If you are using the simulator, select
will interfere with programming the AVR, there are some solutions Simulator as the tool instead. If using a “hobby” programmer, read
to this problem. Of course, those readers who have a debugWIRE on to be prompted to load the program to the target ATtiny.
capable USB programmer/debugger, such as the Atmel-ICE, can  
simply put the target AVR into debugWIRE mode, and thereby use The led_count_asm program configures pins PB0 to PB4 as output

78 May & June 2022 www.elektormagazine.com


pins so that the LEDs attached to these pins can be driven on and
off by the program. The program displays an incrementing binary Listing 1: led_count_asm : main.asm
number, or count, on the LEDs starting at 0 (represented by all
LEDs off). When the count reaches its maximum value (all LEDs     ; Set up pins PB0 to PB4 as output pins
on) it wraps around to zero and starts counting up again. Each “off”      ldi     r16, 0b0001_1111
LED represents a binary zero digit or logic 0 level, and each “on”
     out     DDRB, r16
LED represents a binary one digit, or logic 1 level. It is important
     clr     r18             ; Clear count register
to lay out the LEDs as shown in Figure 2 so that the count displays
loop:
correctly with PB0/D1 as the LSB and PB4/D5 as the MSB of the
count value.      out     PORTB, r18       ; Display count on LEDs
       rcall   delay
Build the program and load it to the AVR if you are using the      inc     r18              ; Increment count
physical hardware of Figure 1 and Figure 2. If using an Atmel-ICE      andi    r18, 0b0001_1111 ; Clear unused bits
or AVR Dragon, use the Start Without Debugging icon on the top      rjmp    loop
toolbar of Microchip Studio or keyboard shortcut Ctrl + Alt + F5 ; Delay subroutine
to load the program to the AVR. If the debugger interface is set delay:
up correctly and the chip is in debugWIRE mode, the program      ldi     r16, 0xff
will load and start running. The incrementing binary count will delloop1:
be seen on the LEDs. If using a program-only USB programmer
     ldi     r17, 0xff
such as a hobby programmer, then load the program to the target
delloop2:
AVR using the appropriate function. If the program was typed
     dec     r17
correctly, the circuit wired correctly, and the program was saved
and built after typing it in, you will see the binary count value      brb     SREG_Z, delloop2
counting up on the LEDs and you can use the simulator with the      dec     r16
rest of the text that follows.      brbc    SREG_Z, delloop1
       ret
If you don’t have the physical hardware, you can still see the count
value by using the Simulator in Microchip Studio. The program
can be stepped through by using the Start Debugging and Break
icons. With the simulator started, open the I/O window from the
top menu by clicking Debug Windows I/O, and then click on the
I/O Port (PORTB) item. Step over the program using the Step Over
icon or F10 keyboard key. Look at the PORTB item at the bottom
of the I/O window to see the count value that would be displayed
on the LEDs if they were attached. The count is updated in PORTB
each time that the OUT instruction is stepped over in the main loop.

How the LED Count Assembler Program Works


Half of the led_count_asm program code consists of the delay
subroutine that was used in the LED blink program discussed
elsewhere in the book. This subroutine is called once in the main
loop of the program so that the count on the LEDs is visible to the
eye without flashing past too fast. Have the led_count_asm project
open in Microchip Studio, with the code from main.asm also open Figure 3: ATtiny13(A) and ATtiny25/45/85 I/O port registers.
while following the explanation of the code that follows.
 
The first two instructions of the program are used to set pins PB0
to PB4 as output pins to drive the LEDs by setting bits in the DDRB
register. Figure 3 shows the DDRB register at the top of the figure. corresponding pin becomes an input pin which is the default of all
Each bit in this register corresponds to a pin on the microcontroller. pins at power-up or reset. At the top of the program, 0b0001_1111
For example, bit DDB0 corresponds to pin PB0, DDB1 corresponds is first written to register R16, and then written from R16 to the
to pin PB1, and so on. DDRB register using the OUT instruction. It is necessary to first
  load the constant value to R16 because there is no instruction to
When a bit in DDRB is set to logic 1, the corresponding pin directly write a constant value to an I/O register such as DDRB.
becomes an output pin. If a bit in DDRB is cleared to logic 0, the Writing 0b0001_1111 to DDRB sets bits DDB0 to DDB4 making pins

lektor May & June 2022 79


PORTB are both used to set up and control port B of the microcon-
troller in both programs. The LED blink program only needs to
control a single pin, so uses the SBI and CBI instructions to set and
clear a single bit in the I/O registers directly — none of the working
registers R0 to R31 are needed for this. The LED count program
needs to access five LEDs or pins at the same time so uses the OUT
instruction to write to multiple bits in a register at the same time.
 
Register usage is important to keep track of in an assembly
Figure 4: Inserting a Breakpoint in the Microchip Studio Debugger. language program. For example, an immediate value is loaded to
R16 at the beginning of the program. R16 is only used temporarily
in this instance, so can be used later in the program without the
PB0 to PB4 output pins. need to first save its value. It is used again in the delay subrou-
  tine. Because R16 and R17 are used in the delay subroutine, R18
Although there are four registers for controlling I/O port B, only was chosen to hold the count value and is not used for anything
three are shown in Figure 3. The fourth register, MCUCR has only else. This ensures that the count value is never overwritten. If
one bit that applies to port B. This bit is a global pull-up disable bit a program gets very big and there are no spare registers to use
that we do not use in this chapter. Refer to the Register Description for dedicated purposes, then PUSH and POP instructions can be
part of the datasheet in the I/O Ports section to see this regis- used at the start and end of a subroutine to preserve the values
ter — use either the datasheet for the ATtiny13, ATtiny13A, or in registers that are used.
ATtiny25/45/85.
  Using a Breakpoint in the Debugger
R18 is used in the program to hold an incrementing count value With the simulator, or the physical hardware and a hardware debug-
that is displayed on the LEDs. R18 is cleared to 0 using CLR before ger such as the Atmel-ICE, use the debugger to step through the
the main loop so that the count starts from 0. program by clicking Start Debugging and Break as we have done
  before. View the I/O port registers by opening the I/O window
In the main loop, the contents of R18 are sent to the PORTB register in Microchip Studio. With the debugger running, select Debug
using the OUT instruction. The PORTB register can be seen in the Windows I/O and then click I/O Port (PORTB) in the I/O window as
middle of Figure 3. Again, each bit in this register corresponds to a shown in Figure 4.
pin on the microcontroller. For pins that were set up as output pins  
using DDRB, the logic levels written to the PORTB register appear When program execution enters the main loop, it is convenient to
on these pins. For pins that are set up as input pins, a logic 1 in place a breakpoint on the RJMP instruction and execute the entire
PORTB enables an internal pull-up resistor on these pins. A logic 0 loop by clicking the Continue toolbar button (keyboard key F5). A
disables the pull-up resistor on the corresponding pin. breakpoint can be placed on the RJMP instruction by clicking the
  gray area at the very left of the instruction and of the Microchip
Because pins PB0 to PB4 are set up as output pins, the count value Studio window. This places a red dot in this area indicating that
written to PORTB appears on these pins as logic levels that switch a breakpoint has been set on the instruction, as can be seen in
the LEDs on and off. A logic 1 in the count value switches the corre- Figure 4. Alternatively, click the instruction that you want to place
sponding LED on, and a logic 0 level in the count value switches a breakpoint on so that the cursor is placed on it, and then select
the corresponding LED off. Debug Toggle Breakpoint from the top menu, or use the F9 keyboard
  key. Once the breakpoint is set, use the Continue toolbar button or
After the count value is written to PORTB using the OUT instruction, press F5 to step though the entire loop and only break at the bottom.
the delay subroutine is called to leave the count value on the LEDs In this way, the count can be seen incrementing by 1 in the PORTB
for a while. Register R18 is then incremented by 1 using the INC in the I/O window as well as in register R18 in the Processor Status
instruction so that the count value that it is holding increments. window, without having to individually step over each instruction
ANDI is used to clear the top three bits of the count value in R18, in the loop.
by using a mask value of 0b0001_1111. This ensures that these  
top bits are always zero. Back at the top of the loop when R18 is Remove the breakpoint from the RJMP instruction by clicking the
written to PORTB again, 0 is always written to the top three bits, red dot at the left of the instruction, or use the menu or F9 to toggle
because they were cleared using ANDI. When the end of the loop the breakpoint off, assuming that the cursor is on the RJMP instruc-
is reached at the RJMP instruction, program execution starts at the tion line. Put a breakpoint on the INC R18 instruction. Now use
top of the loop again, with the new count value written to PORTB, F5 to step through the loop. The new breakpoint ensures that the
and displayed on the LEDs. PORTB register and R18 contain the same value when program
  execution stops. If program execution stops on RJMP, then R18 is
Some things to note about this program: I/O registers DDRB and incremented before writing its new value to PORTB, thus they are

80 May & June 2022 www.elektormagazine.com


unsynchronized when observing these values in the debugger
windows in Microchip Studio. RELATED PRODUCTS
 
The software released by the author in support of the book is
available for free downloading. Head over to [1], scroll down to > Book: W. Smith: Explore ATtiny Microcontrollers using C
the Downloads, and click on the file name: Software_Explore ATtiny and Assembly Language (SKU 20007)
Microcontrollers using C and Assembly Language. Save the ZIP archive www.elektor.com/20007  
file locally (approx. 29 kB) and then extract it. > E-Book: W. Smith, Explore ATtiny Microcontrollers using C
220045-01 and Assembly Language (SKU 20008)
www.elektor.com/20008
Contributors
Text and Graphics: Warwick Smith
Editor: Jan Buiting
Layout: Giel Dols

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

WEB LINK
[1] Book resources/info page: www.elektor.com/20007

Rigol_EN_MSO5000_185x124+3_042022_V01.qxp_Layout 1 13.04.22 14:50 Seite 1 Advertisement

Ultra Vision II Technology

Digital Oscilloscopes:
Powerful and Economical

MSO5000 Series
Digital High-End Oscilloscopes

• Including Bode diagram display


• 70, 100, 200 and 350 MHz Analog Bandwith
(per Software Upgrade)
• 2 (70/100 MHz) or 4 Analog Channels (Upgrade)
+ 16 Digital Channels (MSO)
• Up to 8 GS/sec. Real-Time Sample Rate
• Up to 200 Mpts Memory Depth*
Immediately available → from € 809,- plus VAT • 500.000 wfms/sec. Waveform Capture Rate
Benefit now from currently reduced prices Special Offer → For free until 30.06.2022:
on selected models of the series! Protocol Analysis, Waveform Generator, Power Analysis
*Option

For more information


X-IN-1 please contact your www.rigol.eu
WORKSTATIONS local RIGOL Partner: www.rigol-uk.co.uk www.lambdaphoto.co.uk

lektor May & June 2022 81


regular

Err-lectronics Corrections, Updates and Readers’ Letters


Compiled by Ralf Schmiedel and Jens Nickel (Elektor)

+4V5
Driving Motors with H-Bridges
Elektor 01-02/2022, P. 6 (210491)
Unfortunately, the H-bridge with relay
diagram in this article (Figure 4) is missing
S1 S2
FWD BWD
a connection between the Motor M- and
the common switched contacts of relays K3
and K4. We have included here a corrected
version of the diagram. Many thanks to
the eagle-eyed readers who spotted this
blooper. D1 K1 D3 D5 K3 D7
 
Another error crept into the descriptions M1
of Figure 14 and 20. The chip shown is M
actually an L298N device and not an L294N
as suggested in the description. D2 K2 D4 D6 K4 D8

 
The last two diagrams shown in Figure 23
do not show the correct sequence of field
excitation and rotor orientation. Here is
210491-004

the correct picture:

Simple Earth-Leakage Tracer A Compass Rose... Electronic Load for DC and AC


Elektor 1-2/2022, P. 106 (200576) Elektor 09-10/2021, P. 78 (200597) Elektor 09-10/2021, P. 20 (191206)
It is essential that the Earth leakage I found your article concerning the GY-271 The schematic (Figure 2) indicates that
tracer unit described in this article is compass module very interesting, but I am the Zener diode D3 shown on page 23 has
only used to test equipment which has not sure why it’s necessary to move the a 3.3-V reverse voltage threshold, but it
been completely isolated from the mains sensor through a figure-of-eight pattern? should in fact have a 10.0 V threshold.
supply. It could prove deadly if is used on Jac Hettema 220052-01
any piece of equipment that is powered up  
from the mains! The ground fault meter I did some research to discover if there
works well for troubleshooting problems is a way I could improve a smart phone’s
on portable devices, but only when they compass accuracy and found several web
are in a de-energized and isolated state. sites including this one: https://bit.ly/3rQfdYJ​.
Jörg Stäudle Some cell phone experts say that moving
  the sensor in a figure eight pattern Questions or Comments?
Thanks for emphasizing that point Jörg. ensures that it is rotated twice through If you have any questions or comments,
You are absolutely correct. 360° and serves to perform calibration. please let us know. You can reach us by
The Editorial Team Rolf Hase (Author of the article) email at [email protected].

82 May & June 2022 www.elektormagazine.com


project

LoRa GPS
Tracker Update
Receive and Show Location
Using a Raspberry Pi
By Hans Schneider (Germany) that the reader is familiar with entering commands using the Raspberry
Pi Terminal app. Next, we need to log into the terminal via SSH, by
The article, “LoRa GPS Tracker,” featured using the following command line: bash <(curl -sL https://raw.
in the 6/2020 edition of Elektor described githubusercontent.com/node-red/linux-installers/master/
how to collect the tracking data from a TTN deb/update-nodejs-and-nodered). You may need to enter sudo
apt install build-essential git so that npm is able to build the
server using Node-RED and then visualize it binary modules that need to be installed. The script takes some time
on a map. In principle, this should work, not to run; you should expect it to take around half an hour to complete.
only with a PC, but also with a Raspberry Pi.  
When the Script is finished, the command sudo systemctl enable
Indeed this is possible, but there are one or nodered.service can be input via the Terminal so that Node-RED
two hurdles that need to be overcome. One starts automatically when the Raspberry Pi is powered up or rebooted.
of our readers found a good solution and This command can be disabled by entering sudo systemctl disable
nodered.service.
describes how he ported the Node-RED flow  
to the single board computer. The Node-RED server can be started using node-red-start, and
stopped with node-red-stop. To stop and restart the server use
In the article, “LoRa GPS Tracker” (Elektor, Nov/Dec 2020), Mathias node-red-restart. The terminal can be exited after starting Node-RED,
Claussen describes hardware and software that can be used to track and the server will continue to run. When the terminal is restarted, you
moving objects. A compact tracker module sends the data from a can start the output service of the server using node-red-log and see
GPS sensor via LoRa to a gateway, which forwards it to a The Things the output in the terminal. This is useful if you want to check if everything
Network server, where the raw data can be called up manually via the is still working without starting a new instance of the server.
Internet, provided the necessary authorization is granted. Of course, this
is more convenient when it is accessed automatically via a framework Installing the Required Modules in Node-RED
such as Node-RED, which can also control the display on a (world) The modules can be installed in Node-RED by using either the palette
map. The Node-RED-Flow described in the article works very well on manager in the browser window or by using the npm package manager
a PC, but this has one major drawback: an energy-guzzling PC needs from the terminal. My recommendation would be to use npm because
to be powered up for this purpose and we need the Node-RED server in my experience that works more reliably. In this case, however,
running, otherwise we will get no data. Node-RED must be terminated beforehand.
   
It’s likely that many tech-savvy households will already have at least one If, on the other hand, the Node-RED service runs on the Raspberry
Raspberry Pi on which software such as Pi-Hole [1], Homebridge [2] Pi, you can log into the user interface using a browser on the PC. For
or Flightradar24 [3] is running and continuously waiting to receive and this, you need to enter the address line: http://<IP-address of
send data. Why shouldn’t we entrust another task to this Raspberry Pi? Raspberry Pi>:1880 , which will get you into the Flow-Editor. The
One note of warning: the resources used by Node-RED can sometimes required modules are installed here first; in the Flow-Editor, this is
conflict with a Homebridge installation. With that in mind, the instal- done via the palette manager. The modules you will need are (some
lation procedure is also not entirely without difficulties. of them were already installed when installing Node-RED):
 
Installing Node-RED on the Raspberry Pi > node-red
First, we need to install Node-RED on the Raspberry Pi. It is assumed > node-red-contrib-worldmap

lektor May & June 2022 83


Figure 1: MQTT-Node in Node-RED.
> node-red-node-rbe
> node-red-node-sqlite
> node-red-node-base64
> node-red-tail
 
Some patience is called for here when installing via the Palette
Manager; if the activity monitor has been hidden, it takes a while
before the success message pops up at the top of the window.
 
If the installation via the Palette Manager is unsuccessful, exit the
Editor again, and in the Terminal, stop the Node-RED service on the
Raspberry Pi and do it manually. For example, the statement npm
i --unsafe-perm node-red-node-sqlite installs the node-red-
node-sqlite module, and you can do the same for the other modules.
Figure 2: MQTT-node server property setting.
 
If node-red-node-sqlite does not install the node-red-sqlitedb,
it will need to be installed afterwards. This is only possible via npm,
because in this case the Palette Manager detects a conflict with the
node-red-node-sqlite module.

The Missing TTN Module


So far, so good. At this point, you may have noticed that the TTN-Mod-
ule (The Things Network) discussed in the original article is missing.
The reason is it is not supported by the Raspberry Pi environment. For
example, once node-red-contrib-ttn has been loaded it is no longer
possible to start Node-RED-Service on the Raspberry Pi. It took me
a while to figure this out, but I’m glad now I can pass this on to save
you the stress of that particular troubleshoot.
 
The solution lies in the mqtt module built into Node-RED. It is included
in the origin flow instead of the TTN uplink module. You can download
Figure 3: Add a new Server. and use my flow, which is specially adapted for the Raspberry Pi from
the LoRa GPS Tracker page [5] at Elektor Labs. The flow is imported
by simply dragging the downloaded JSON file into the Flow Editor
window. By the way, this flow adapted for the Raspberry Pi also runs
on the PC in place of the flows with the special TTN nodes.
 
Using the Flow Editor, you can now double-click on the mqtt symbol
(Figure 1) and edit the settings in the window that opens (Figure 2).
Now “v3/+/devices/+/up” is entered under Topic as shown in the
figure in order to receive the data of all devices in the TTN applica-
tion. As Output you can keep the default configuraton “a parsed JSON
object”. A new server can be entered in the Server field by using the
pencil symbol and the window shown in Figure 3 opens.
 
The Application ID from the TTN Console is used as the Name, and
eu1.cloud.thethings.network is the Server. The default port is 1833
(MQTT without TLS) which needs to be changed to 8883. Lastly, what’s
missing is the checkmark next to Enable secure (SSL/TLS) connec-
tion. A click on the pencil symbol of the TLS Configuration field calls
up the next window (Figure 4).
 
Figure 4: TLS configuration of the new Server. Now the settings can be accepted by clicking on Add. Back in the
mqtt-broker config node window, select the Security tab (Figure 5).

84 May & June 2022 www.elektormagazine.com


Figure 5: Access key management of the MQTT nodes.

Figure 6: The finished flow diagram in Node-RED.

The Username is the Application ID from the TTN console with @ttn
appended. An access key with at least “Messages Rights” must be RELATED PRODUCTS
generated as the password in the TTN console. The Access Key copied
from the TTN console is then pasted under Password and confirmed by
clicking on Add. Back in the mqtt in element, you can give the element
> Elektor LoRa Node – Partly Assembled Module
(SKU 19175)
a name (e.g. TTN uplink); lastly a click on Done completes the task. www.elektor.com/19175  
 
Figure 6 shows the updated Node-RED flow chart. The CayenneLPP > SeeedStudio RFM95 Ultra-long range LoRa Transceiver
decoder shown in the flow is included for future system expansion. Module (868 MHz) (SKU 18715)
www.elektor.com/18715  
210120-01

> Dragino PG1301 LoRaWAN GPS Concentrator for


Raspberry Pi (868 MHz) (SKU 19367)
www.elektor.com/19367
Contributors
Idea and Text: Hans Schneider
Editors: Mathias Claußen, Jens Nickel, C.J. Abate
Translation: Martin Cooke
Layout: Harmen Heida WEB LINKS
[1] M. Claußen, “LoRa GPS Tracker,” ElektorMag 11-12/2020:
www.elektormagazine.com/lora2020
Questions or Comments? [2] Pi-hole: https://pi-hole.net
If you have any questions or comments regarding this article, you [3] Homebridge: https://homebridge.io
can contact the author at [email protected] or the [4] Flightradar24: www.flightradar24.com/
team at Elektor at [email protected]. [5] “LoRa GPS Tracker,” Elektor-Labs.com:
www.elektormagazine.com/labs/lora-gps-tracker

lektor May & June 2022 85


elektor books

Circuit Simulation with


TINA Design Suite & TINACloud
Sample Chapter: Sinusoidal Oscillators
By Dogan Ibrahim (United Kingdom)

Reportedly, one of the best features of TINA is that a simulated circuit can easily be
implemented on a PCB with auto-placement and auto-routing capabilities. Users can also
use the Gerber plotting and CNC drilling options of TINA to learn, design, and implement
a prototype of their projects. That’s “awesome,” but before any PCB can come into play, you
have to master elementary circuit simulation. Here’s an up-tempo primer to TINA you
cannot afford to miss and do on your PC.
 
A sinusoidal oscillator consists of an amplifier and a feedback The total loop phase shift is, therefore, 0° as required for oscillation.
network (Figure 1). The following two conditions must be satis-  
fied to have a working oscillator: TINA schematic
Figure 2 shows the circuit diagram. The RC network is connected
> the loop gain (A × B) in Figure 1 must be greater than or equal to the inverting input of the operational amplifier. Assuming the
to unity; resistors and capacitors are the same, the requirement is that the
> the total phase shift around the circuit must be 0 or 360°. voltage gain of the amplifier must be greater than or equal to 29, i.e.:
 
Rf
Some simulations of operational amplifier-based oscillator circuits Gain
  29
are given in this section. R

Simulation 1 — Phase-shift Oscillator The frequency of oscillation is given by:


This is sometimes called the RC oscillator. Each RC pair introduces
a 60° phase shift. Three resistors and capacitors are used here to 1
f 
introduce a 180° phase shift to the feedback loop. 2 RC 6

86 May & June 2022 www.elektormagazine.com


Editor’s Note. This article is an excerpt from the 440-page book Circuit Simulation with
TINA Design Suite & TINACloud (Elektor 2022). The excerpt was formatted and lightly
edited to match Elektor Mag’s editorial standards and page layout. Being an extract from
a larger publication, some terms in this article may refer to discussions elsewhere in the
book. The Author and Editor have done their best to preclude such instances and are
happy to help with queries. Contact details are in the Questions or Comments? box.

Figure 1: Oscillator principle. Figure 2: Circuit schematic.

In this example, the required frequency is 4 kHz. Choosing C = configuration is employed.


2 nF, we can find the required value of R from:  
The condition for oscillation is that the voltage gain must be greater
1 1 than or equal to 3.
R 
2 f C 6 2  4 10  2 109  6
3  
Assuming the same resistors and capacitors are used, the frequency
which gives R = 8.12 kΩ. Then, of oscillation is given by:

Rf 1
 29 f 
R 2 RC

and we choose Rf = 237 kΩ. A type UA741 operational amplifier In this example, the required frequency is 5 kHz. Choosing C =
is used in this project. The TINA circuit is available as a file sim9 3 nF, we can find the required value of R from:
(see article end).
  1 1
R 
TINA simulation 2 f C 2  5 103  3 109
The steps to run the simulation are:
  which gives R = 10.6 kΩ.
> Click T&M -> Oscilloscope and Run. Set the Time/div to 100 u.
> Check the output waveform (Figure 3). The period is 250 µs
which corresponds to 4 kHz. Note the glitch in the output
waveform on the oscilloscope. The oscilloscope can be
synchronized to create a stable picture. To do this, select
Normal under Mode and synchronizing signal under Source. It
may also be needed to set the (Trigger) Level.

Simulation 2 — The Wien Bridge Oscillator


This is one of the simplest sinusoidal oscillators. The Wien Bridge
oscillator is a two-stage RC coupled circuit that has good stability
at its resonant frequency, low distortion, and is very easy to tune,
thus making it a popular circuit as an audio frequency oscillator.
 
The circuit uses a series RC connected with a parallel RC. The phase
shift of the circuit is 0° at the resonant frequency, and the circuit
is connected to the positive input of the operational amplifier so
that the overall phase shift is 0°. Usually, a non-inverting amplifier Figure 3: Output waveform.

lektor May & June 2022 87


Figure 4: Circuit schematic. Figure 5: Output waveform.

 
To satisfy the gain condition, for a non-inverting amplifier (see 1
f 
Figure 4): 2 LCT

Rf Where CT is the series combination of C1 and C2, i.e.:


Gain  1 
R2
C1 C2
CT 
Choosing Rf = 100 kΩ: C1  C2

Rf The amount of feedback depends on the values of C1 and C2.


1 3
R2 Therefore, by changing the values of these capacitors, we can adjust
the amount of feedback voltage returned to the tank circuit. The
Which gives: ratio of C1 to C2 is the feedback ratio, B:
 
Rf B = C1 / C2
R2
  50 K
3 1  
For oscillations, AB ≥ 1, where A is the amplifier gain.
Choose R2 = 47 kΩ.  
  Or, A ≥ C2 / C1.
TINA schematic  
Figure 4 shows the circuit diagram. The feedback circuit is In this example, the required frequency is 10 kHz. Choosing L =
connected to the noninverting input of the operational ampli- 10 mH we can find the feedback ratio from:
fier and the gain is set through Rf and R2. A type UA741 opera- 1 1
tional amplifier is used in this project. The circuit is available CT 
4 f L 4  10  10 103
2 2 2 8
as a file: sim10.
 
TINA simulation which gives 25.3 nF.
The steps to run the simulation are:  
Choosing C2 = 250 nF gives C1 = 28.15 nF, which corresponds to a
> Click T&M -> Oscilloscope and click Run. Set the Time/div to feedback ratio of B = C2 / C1 = 250 / 28.15 = 8.88.
100u.  
> Check the output waveform (Figure 5). The period is 200 µs We can therefore choose the amplifier gain to be around 10 (see
which corresponds to 5 kHz. Figure 6), giving:
Rf
  10
Gain
Simulation 3 — The Colpitts Oscillator R1
The Colpitts oscillator uses a capacitive voltage divider network as
its feedback source. Two capacitors, C1 and C2 are placed across a Choosing R1 = 5 kΩ gives Rf = 50 kΩ.
single common inductor, L, where C1, C2, and L form the tuned tank  
circuit. The feedback circuit is usually connected to the negative TINA schematic
input. C1, C2, and L provide the additional 180° phase shift required Figure 6 shows the circuit diagram. The feedback circuit is
to make the total phase shift 0°. connected to the inverting input of the operational amplifier and
  the gain is set through Rf and R1. A type UA741 operational ampli-
The frequency of oscillation is given by: fier is used in this project. The circuit is available as a file: sim11.

88 May & June 2022 www.elektormagazine.com


Figure 6: Circuit schematic. Figure 7: Output waveform.

 
TINA simulation
The steps to run the simulation are:
  RELATED PRODUCTS
> Click T&M -> Oscilloscope and Run. Set the Time/div to 50u.
> Check the output waveform (Figure 7). The period is 100 µs
(100u) which corresponds to 10 kHz. > Book: D. Ibrahim,  Circuit Simulation with TINA Design
Suite & TINACloud (SKU 19977)
www.elektor.com/19977  
Where to get it?
The TINA simulation files mentioned in this article are contained > E-Book:  D. Ibrahim,  Circuit Simulation with TINA Design
in the software bundle released by the author and DesignSoft in Suite & TINACloud (SKU 19978)
support of the book. The software is available for free download- www.elektor.com/19978  
ing. Head over to [1], scroll down to the Downloads, and click on
this file name:
Contents_Circuit Simulation with TINA Design Suite & TINACloud.
 
Save the ZIP archive file locally (2.45 MB)) and then extract it.
Open your version of TINA and load the files sim9, sim10, sim11 as
mentioned in this article. Feel free to modify them for your own
applications.

Limited Time Offer: The TINA book comes with a free, one-year
license of TINA Cloud Basic Edition.
220025-01

Contributors
Text and Graphics: Dogan Ibrahim
Editor: Jan Buiting
Layout: Giel Dols

u b li c a t io n s c ome with
Questions or Comments? Both p r License
Do you have any technical questions or comments related to this
E E o n e -y e a
a FR
article? Email the author at [email protected] or Elektor
I N A C lo u d B a sic Edition
at [email protected].
for T r).
(Limited Offe

WEB LINK
[1] Book resources/info page: www.elektor.com/circuit-simulation-with-tina-design-suite-tinacloud

lektor May & June 2022 89


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

From Life’s
Experience
Assembly Line Work
By Ilse Joostens (Belgium)

Quite some time ago, I made the switch from


the “good old” through hole technology to SMT
components. Despite some initial trepidation, Photo: Yekatserina Netuk / Shutterstock.

working with these horribly tiny parts turned out


to be not as bad as imagined and soon I began
dreaming about having my designs manufactured. appeared they were pushed onto the circuit
The latter turned out to be a big disappointment board with some considerable force. Now this
however, and before I realised it, I spent entire days hours-long rework of such circuit boards is not
immediately the most productive activity and
manually assembling circuit boards with tweezers, most certainly not when there is some time
real drudgery therefore. It became so bad that even pressure because customers are waiting for it.
when I closed my eyes I continued to see the assembly  
The circuit boards themselves were also of
line of SMT components moving along. And it will not questionable quality. It was almost impossi-
surprise you that I had a slightly annoyed response ble to desolder components without lifting
when for my birthday I received a diamond painting, the copper pads as well. Broken traces and
inadvertent short circuits between traces
ostensibly for relaxation. According to the seller’s also made their appearance every now and
website, diamond painting is stress-relieving and then. When I became truly fed up with this
you can make master pieces that take your breath and conveyed this to my German supplier, he
shrugged his shoulders and said nonchalantly:
away. Maybe that is so, but to me it looks suspiciously “Chinese quality!” For my own products, I
similar to SMT assembly. didn’t want to fall into that trap and decided
to go with European suppliers. The quality was
perfectly fine, but now instead of the familiar
Grit such as ceramic capacitors for the decoupling smoke signals, there were other dark clouds
A little over 10 years ago, I worked with a of the power supply rails. Unfortunately, the along the horizon.
small German company and they had all Chinese contract assembler took the term
their circuit boards assembled in China. If “grit” a little too literally. It appeared that the Chocolate Cake
you are active in the electronics sector, you components were merely thrown on the board I normally ordered my circuit boards for proto-
are likely familiar with the concepts of “grit” or from a distance and many were on an angle types from a European PCB manufacturer,
“chicken feed”. This is a euphemism for those or mounted the wrong way around, and then because the wait times would otherwise be
cheap passive components that are normally  don’t even mention the solder connections. too long. Even with larger production quanti-
mounted in large numbers on a circuit board, Some components were even cracked, and it ties the higher price was still acceptable,

90 May & June 2022 www.elektormagazine.com


because the cost of the circuit board is only Geopolitics Nevertheless, it doesn’t feel right, because
a small part of the total cost of a product. It is These days we normally order our circuit apart from the pricing, there is very little that
of course important to avoid multi-layer circuit boards from the Far East, mainly because of is democratic in China. Their worldwide expan-
boards and solder masks in fancy colours some pressure from our customers to keep sion drive and geopolitical developments in
as much as possible. But after a while that prices down. And yes, it goes well, although recent years make them just a little less sympa-
green solder mask looks a bit boring, and I the quality is perhaps a little lower, but in any thetic. So, I will store my tweezers not too far
was secretly a little envious of the circuit boards case certainly acceptable, and we can finally away.
in fancy colours from the competition. choose from a range of fancy colours without   220031-01
  an immediate financial penalty.
SMT assembly on the other hand was a big   Questions or Comments?
disappointment, with the high set-up costs In the past few years, we have, despite every- Do you have any technical questions
being an absolute killer. Just the manufactur- thing, been able to have some products or comments prompted by this article?
ing of the stencils for the solder paste printer assembled, including the sand clock and the Send an email to the editor of Elektor via
already ran into the hundreds of euros, and that Swiss Pi [2] expansion board for the Raspberry [email protected].
is not counting the documentations costs, the Pi. For a while now, the assembly quality in
set-up costs for the SMT assembly machine, China has improved immensely, despite the
and the Automated Optical Inspection (AOI) democratically low prices and ditto set-up Contributors
as well. costs. Other services too, such as 3D print- Text: Ilse Joostens
  ing and CNC machining of various materials Editor: Eric Bogers
Unfortunately, my volumes were such that it are offered, so that it becomes very tempting Translation: Arthur de Beun
was too much to assemble everything myself to place orders there. Layout: Giel Dols
by hand and too few to cover the costs of  
automated assembly. And so many a lonely
evening in the attic room was my lot. Besides
the repeated looking for the required parts, it
was the application of solder paste to the circuit
board that was the most cumbersome task.
To make it easier for myself, I normally cut a
window in a piece of 3‑mm thick perspex that
fits the circuit board exactly. With two circuit
boards stacked on top of one another, the top
board is pretty much flush with the perspex
and the stencil can be positioned in the correct
location and secured in place with some tape.
Only the solder paste is a mess to work with
every time. It doesn’t matter how carefully you
work, but after a number of circuit boards, the
table and your hands are covered in solder
paste and with a bit of bad luck it is also on your
clothes. You know the classic image of a baby
who has just eaten a piece of chocolate cake,
where the baby as well as the high chair are
covered in chocolate [1]. After the application
of the solder paste, a similar feeling overcomes
me and with a big sigh start with the cleanup. Photo: Oleg Shvydiuk / Shutterstock.

WEB LINKS
[1] “Is cake smashing the dumbest cake trend ever?”, Anges de Sucre/Anges Bakery: https://bit.ly/3nyQeGD
[2] P. S’heeren, “Swiss Pi – A Swiss Army Knife for the Raspberry Pi,” Elektor 09-10/2016:
https://www.elektormagazine.com/magazine/elektor-201609/39796

lektor May & June 2022 91


software

The WinUI Graphics


Framework for Windows Apps
A Small Demo Application

By Dr. Veikko Krypczyk (Germany)

Software designed to control various electronic applications often runs


in a Windows environment. Using a locally installed desktop application
gives you direct access to all of the PC’s system interfaces. Microsoft is
currently rationalizing its support for developers working with Windows
interface frameworks. The new graphics interface WinUI 3 is the way
forward. Here, we will take a look at the technical background and show
how to use it by building a small demo app for electronics technicians.

For many electronics projects, a Windows PC is used to provide control the .NET framework, which was intended for Windows programs and
functions, data logging and other tasks; it will typically be necessary to whose further development ended at version 4.8.
develop a graphical user interface to run under Windows to carry out this  
function. Locally executed desktop applications are often the method of Version .NET 5, on the other hand, is the technological successor to
choice here; they give you complete access to the system environment .NET Core. This framework is not limited to Windows, but can also be
and, via the appropriate drivers, also provide links to connected peripherals. used with other operating systems. Microsoft has surprisingly trans-
  formed both WinForms and WPF to .NET Core. If you are creating an
Microsoft, as the manufacturer of the Windows operating system, is app for Windows today and opt for WinForms or WPF, then you have
currently undergoing a major technological upheaval. The focus of the choice between the previous .NET framework and .NET Core. It
this activity is on the connectivity and design of user interfaces. The is also possible to migrate existing applications, but, as is so often the
developments are coordinated under the project names WinUI 3 and case with such projects, it is often associated with a number of issues.
Windows App SDK. In this article, we show what this new graphic inter- Other manufacturers of development tools for Windows applications
face is all about and where we can use it. First, we get an overview of have mostly based them on the graphic interface of the operating
the possibilities of programming Windows applications with a graphi- system (GDI) and encapsulated this in their own framework.
cal user interface. The purpose of WinUI 3 will become clear by using  
different technologies and application types. Not content with a purely The second category of Windows applications are apps for the Univer-
theoretical review of this relatively new type of Windows application, sal Windows Platform (UWP). These run in an individually isolated area
we will also go ahead and create our first practical application. of ​​the operating system and have only limited system access. Users
install these apps through the store. In practice, however, this type of
The Technology app has not proved to be popular and its uptake is quite low. One of the
Basically, current applications using a graphical user interface for the reasons for this is that system access from these apps is very limited.
Windows operating system can broadly be divided into two types. On The UWP however has the advantage that the graphics framework
the one hand, we have Desktop Applications. These are essentially based WinUI 2 used here is significantly more modern than the technologies
on the use of the Win32 API. There are different approaches, frameworks of WinForms and WPF. An appealing design, new visual components,
and programming languages ​​for their development. The technologies the use of materials and the orientation towards the design language
Windows Forms (WinForms) and Windows Presentation Foundation Fluent Design System are its stand out features. In other words, apps
(WPF) come from Microsoft. WinForms relies on the Windows GDI inter- for the UWP look modern, contemporary and fresh, but their usability
face. WPF is based internally on DirectX and was originally intended as is somewhat limited. To achieve similar effects with the WinForms or
a replacement for WinForms. Both graphics frameworks were based on WPF technologies, we need to do some pull-ups, use extensive third-

92 May & June 2022 www.elektormagazine.com


Figure 1: App: WinUI 3 Controls Gallery.

 
party components or “mix” the WinForms/WPF technologies with the > Separation of code and design: The user interface is declaratively
UWP. This approach however quickly leads to a more complex app created in separate files using the XML-based XAML language.
structure and brings with it the typical disadvantages, such as higher > UI control elements: A range of controls are available for design-
susceptibility to errors and poorer maintainability. ing the user interface. These include basic elements such as
  buttons and text entry fields, along with more complex and
Software designed for electronic control, development, etc., are advanced elements such as a calendar control element, a
almost without exception classic desktop applications. You can also WebView or an element for displaying personal data, which we
build these using other tools and frameworks. For the program- can use, for example, for user administration. If you would like to
ming language Java there is, for example, the graphics framework explore the range of control elements further go to the Micro-
Swing, which for Windows is based internally on the GDI operat- soft Store and download the WinUI 3 Controls Gallery app from
ing system interface. there. This app gives a preview of the available controls for WinUI
3. Their use (Use Case) and their integration in the source code
The WinUI 3 Graphic Framework (XAML) are demonstrated. Corresponding links to the documen-
With the introduction of the WinUI 3 graphic interface, Microsoft tation can also be found (Figure 1).
would like to enable all applications under Windows to use a modern > Loose coupling through DataBinding: The properties and events
graphic interface. WinUI 3 is the technological successor to WinUI 2 of the control elements are linked to the source code by means
[1]. However, it is available for all types of Windows applications and of data binding. In this way, data is exchanged in both directions
is therefore not limited to use in apps for the UWP. WinUI 3 is part between the program code and the user interface control. Events
of the new Windows App SDK, which is also provided in parallel of the control elements, such as the click on a button, are also
with the introduction of Windows 11. The Windows APP SDK bundles forwarded to the relevant algorithm in the same way.
new features for the development of Windows applications. It is not > Modern Design: The WinUI 3 provides a contemporary feel.
only aimed at Windows 11, but can also be used under the current This includes the use of Microsoft’s design language Fluent
versions of Windows 10. Development of the Windows App SDK is Design System with the Mica material introduced in Windows 11.
still ongoing, but a first version is available that can already be used The Fluent Design System provides the following UI elements:
in newly created applications. conscious use of geometry and colour, overlapping of surfaces,
  use of selected materials and the use of specific iconography and
WinUI 3 is technically and conceptually based on WinUI 2. If you have typography for visual design using images, symbols and fonts.
ever developed an app for the UWP, you will quickly get to grips with Motions between UI elements are also supported.
it. It is based on the following principles:  

lektor May & June 2022 93


Figure 2: Select the necessary Workloads for Visual Studio.

Let’s look at the procedure for developing applications with the WinUI 3.
First, we will need to set up the development environment.

The Development Environment and Setup


The current version of Visual Studio 2019 [2] will be used as the devel-
opment environment. The Community Edition will be sufficient for our
needs. By the time you’re reading this article, a stable version of Visual
Studio 2022 may already be available, in which case you should use
this version. It is advisable to install the latest updates for the operating
system beforehand. During the installation of Visual Studio, you will
Figure 3: First Start of Visual Studio. be asked to select the installation packages. You can also call up the
Visual Studio Installer at any point later on via the start menu. Now
select the following installation packages (Workloads): .NET desktop
development, Desktop development with C ++ and Universal Windows
Platform development (Figure 2). After installation, start Visual Studio
and in the start screen select the option Continue without code ->
(Figure 3).
 
We now also need to install the template for development with WinUI 3.
To do this in Visual Studio, choose the menu option Extensions |
Manage Extensions. Search here for Project Reunion (the develop-
ment name of the new Windows App SDK) and install the current
version (Figure 4). In the same way install the Windows Template
Studio extension. This offers advanced templates for creating a new
application. Visual Studio must be restarted after the extensions have
Figure 4: Windows SDK App (Project “Reunion”) installation. been downloaded; the installation will then take place automatically.

94 May & June 2022 www.elektormagazine.com


An App for WinUI 3
Let’s start by creating a new project. Here in Figure 5 we select the
App WinUI 3 in Desktop template (Windows Template Studio). In the
Windows Template Studio (Figure 6), we can configure the project:
 
> Project type: Here we specify the type of navigation, for example
with a menu bar or a side navigation bar (Hamburger menu).
> Design pattern: Direct installation and configuration of the MVVM
toolkit. This couples the elements of the user interface (defined in
XAML) with the program logic (programming language C#).
> Pages: We can add a number of pages to the project. We can
choose from different templates, for example one page for enter-
ing program settings.
> Features: Here we can select some sample themes or save
Figure 5: Project template WinUI 3 Desktop.
program settings.
 
By clicking on the Create button, we generate the desktop applica-
tion that WinUI 3 uses. Windows Template Studio generates a project
folder with three projects:
 
> App: This contains the source code for the desktop application.
In the subfolder View, for example, you will find the XAML files for
the pages that were created by Windows Template Studio. The
program logic is stored in files in the ViewModel program folder.
> Package: The project is responsible for providing the desktop
application. At the moment, WinUI 3 applications are installed on
the target computer as an app package. This format has so far
been used for UWP apps. The generated packages can also be
distributed by using Store. Future versions of the Windows App
SDK should also allow installation without an app package.
> Core: This project contains the collection of services and classes
that provide service for the app. This project is not mandatory
and can be left out.
 
Start the application directly from Visual Studio using the green arrow Figure 6: Windows Template Studio.
on the toolbar. Congratulations - You have created your first appli-
cation with WinUI 3 (Figure 7). I should emphasis again; this is a
desktop application with full system access. As already mentioned,
this is important for software designed to control external electron-
ics, for example. A side navigation bar, first pages and the possibility
to adapt the application design are all possible. You have all options
for accessing the system, including communication with the system
libraries and drivers. Now we can go ahead and experiment with the
design of the user interface.

A Demo Application
The best way to become familiar with any new system is to try it out.
Here we will design a simple user interface for our first application (the
source code, for this example, can be found on the web page for the
article [3]). The starting point is the XAML file for the relevant page.
As an experiment we can create a handy calculation tool for use with
the LM317 adjustable linear voltage regulator (Figure 8). The output
voltage of this device is given by the formula Vout = 1.25  (1  +  R2/
R1). We can solve this equation for R2 and thus calculate its value to
give the desired output voltage. With the help of this example we can Figure 7: A first desktop application with WinUI 3.

lektor May & June 2022 95


demonstrate the procedure for programming applications with WinUI
3. This process will include the following steps:
 
> Definition of the User Interface in XAML.
> Coding the Program logic in C#.
> Binding the user interface to the program logic.
> Forwarding the user interaction from the user interface to the
program logic.
> Output the data to the form.
 
Let’s start by defining the surface. We need two text fields to record
the values o​​ f R1 and VOut. We also need a text field for the value of R2.
A Button will be required to trigger the calculation. We use TextBox
controls for input and output. All the elements should be arranged in
the form of a vertical stack one above the other, which is why they are
Figure 8: LM317 voltage regulator circuit diagram. inserted into a layout container of the type <StackPanel />. Without

Table 1: Control Elements


Control
Property Value Description
Element
Width 200 Textbox width
Margin 20, 20, 0, 0 Margin size: left, top, right, bottom
TextBoxR1 HorizontalAlignment Left Left justified
Header R1: Caption
Text x:Bind ViewModel.R1 Binding the property to the variable R1 in C#.
Width 200 Textbox width
Margin 20, 10 Margin size: left, top, right, bottom
TextBoxU HorizontalAlignment Left Left justified
(out) Header U (out): Caption
x:Bind ViewModel.
Text Binding the property to the variable UOut in C#.
UOut
Width 200 Textbox width
Background LightGray Background colour
Margin 20, 10 Margin size: left, top, right, bottom
TextBoxR2 HorizontalAlignment Left Left justified
Header R2: Caption
IsReadOnly True Read only protection
Text x:Bind ViewModel.R2 Binding the property to the variable R2 in C#.
Width 200 Button area width
Margin 20, 10 Margin size: left, top, right, bottom
Background LightGreen Background colour
Button x:Bind ViewModel.
Command Binding to the CalcCommand Method in C#.
CalcCommand
Content Calc Caption
FontWeight Bold Font properties

96 May & June 2022 www.elektormagazine.com


Figure 9: Coding the UI surface in Live-
mode (Hot Reload).

the need for any further configuration, all the elements will be arranged the application is started - without saving — and produce an updated
one above the other with StackPanel. The controls are configured via display. This feature is called Hot Reload and is standard when creat-
the XAML code, with the properties according to Table 1. ing graphical user interfaces.
   
The associated source code is shown in Listing 1. You can code the What is interesting here is the control binding of the control elements of
surface interactively. Start the application and place the relevant XAML TextBox type with the properties of Text. Here you will find an expres-
file in Visual Studio and the application side by side on the screen sion according to the pattern in the XAML code:
(Figure 9). Changes in the XAML code are immediately adopted when  

Listing 1. Definition of User Interfaces

<Page             <Button


    x:Class="App1.Views.MainPage"                 Width="200"
    …>                 Margin="20,10"
                  Background="LightGreen"
    <Grid x:Name="ContentArea" Margin="">                 Command=""
        <StackPanel Background="">                 Content="Calc"
            <TextBox                 FontWeight="Bold" />
                Width="200"             <TextBox
                Margin="20,20,0,0"                 Width="200"
                HorizontalAlignment="Left"                 Margin="20,10"
                Header="R1:"                 HorizontalAlignment="Left"
                Text="" />                 Background="LightGray"
            <TextBox                 Header="R2:"
                Width="200"                 IsReadOnly="True"
                Margin="20,10"                 Text="" />
                HorizontalAlignment="Left"         </StackPanel>
                Header="U (out):"     </Grid>
                Text="" /> </Page>

lektor May & June 2022 97


Figure 10: Example Relationship between View and ViewModel.

Text="{x:Bind ViewModel.R1, Mode=TwoWay, UpdateSource two layers. Thanks to the MVVM concept, all layers are decoupled
Trigger=PropertyChanged}" and can be developed and maintained independently of one another.
  Information on the MVVM pattern can be found under [4].
This means that the property of Text is bound to the variable R1. This is
defined in the ViewModel page and is based on the MVVM concept. Program Logic
UI events are handled in the View layer and data is managed in the The program logic is implemented using C# (Listing 2). For this
Model layer. The ViewModel represents the connection between the purpose, a program file (ViewModel) is assigned to each window of

Listing 2. Program logic for the calculation in C#


            {
using CommunityToolkit.Mvvm.ComponentModel;                 SetProperty(ref r2, value);
using CommunityToolkit.Mvvm.Input;             }
          }
namespace App1.ViewModels  
{        
    public class MainViewModel : ObservableRecipient         public RelayCommand CalcCommand;
    {         public MainViewModel()
        public double R1 { get; set; } = 240;         {
        public double UOut { get; set; }             CalcCommand = new RelayCommand(calcComm
        andExecute);
        private double r2;         }
        public double R2  
        {         private void calcCommandExecute()
            get         {
            {             R2 = (UOut / 1.25 - 1) * R1;
                return r2;         }
            }     }
            set }

98 May & June 2022 www.elektormagazine.com


the user interface (View). In our example, it is the MainViewModel file
assigned to the view MainPage. Here are some notes on the program
code:
 
> Import of libraries: This is done via the uses statement. In our
case we need two libraries for the MVVM pattern.
Figure 11: The finished app example.
> Definition of properties: These must be public because we
access the properties from outside, in this case from the view.
> Automatic User Interface updating: The MainViewModel class
is derived from the ObservableRecipient base class, which was
generated by the project wizard when the project was created.
This class in turn implements the so-called OnPropertyChanged Conclusions and Outlook
event. This ensures that when a value of a property changes, You can choose from a variety of technologies to create an application
all bound elements are notified of the change. In our case the for the Windows operating system. The trend — also with a view to
property R2 is of interest. The value of R2 is calculated in the Windows 11 — is towards the use of WinUI 3. Using this will enable you
program code. The so-called Setter of the property is called and to create an attractive and up to date user interface. From this perspec-
the OnPropertyChanged event just described is triggered via the tive, it is worthwhile considering WinUI 3 when developing any new
SetProperty (…) method. The Text property of the TextBox R2 Windows application and to check migration options for any existing
is bound to the property R2 (in the ViewModel). If R2 is changed, applications. The resulting applications have a contemporary interface
the displayed value is automatically updated in the associated and produce a good user experience. There are also no limitations on
TextBox. This works thanks to data binding. system access as there are with the UWP application model.
> Pass on user actions by means of commands: If the user 210407-01
presses the button, a command is triggered. The calculation  
method is linked to this command. Here, too, the user interface
and program code are only linked to one another via the data link. Contributors
> Assignment of View and ViewModel: The program code (file: Text and images: Dr. Veikko Krypczyk
MainViewModel.cs) is assigned to the UI (file: MainPage.xaml). Editor: Jens Nickel
This is done in the page’s code-behind file (file: MainPage.xaml. Translation: Martin Cooke
cs). You can see this if you take a look at the source code. Layout: Giel Dols
> Calculation: Calculation of value of R2 takes place in the
calcCommandExecute (...) method according to the above
formula, which is then assigned to R2.
  Questions or Comments?
The user interface is therefore “loosely” linked to the program code by Do you have any technical questions or comments prompted by
means of data binding. The connections to data binding just described this article? If so, please contact the editor at [email protected].
are visualized using the example in Figure 10. Start the application
and try it out. The value of the second resistor R2 is calculated after
entering the values of R1 and VOut (Figure 11).
 
We have thus described the basic development model for desktop appli-
cations with the WinUI 3 graphics framework. From today’s perspec-
tive, it will become a new standard under Windows and can also be
used by other development environments and languages. The variety
of graphical options for creating modern applications is impressive.

WEB LINKS
[1] Information for WinUI 3: https://docs.microsoft.com/en-us/windows/apps/winui/
[2] Visual Studio 2019: https://visualstudio.microsoft.com/
[3] Project page for this article: http://www.elektormagazine.com/210407-01
[4] Information for MVVM pattern: https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel

lektor May & June 2022 99


tutorial

Create GUIs
Part 04

with Python:
World’s worst GUI
Learn good GUI design by doing it all wrong first!

I
Laura Sach t’s time to really go to town with your GUIs and visible and show it if it’s not:
MAKER

experiment with different widgets, colours,


Laura leads the
fonts, and features. Like most experiments, it’s def flash_text():
A Level team at
the Raspberry likely that you won’t get it right first time! In fact, if title.visible:
Pi Foundation, you are going to explore the wrong way to approach title.hide()
creating resources creating your GUI. else:
for students
to learn about title.show()
Computer Science. It’s hard to read
@CodeBoom The right choice of GUI colour and font are Before the app is displayed, use repeat to
important. It’s important that the contrast make the flash_text function run every 1000
between background and text colour ensure that milliseconds (1 second).
your GUI is easily readable. What you shouldn't do
is use two very similar colours. app.repeat(1000, flash_text)
Import the widgets at the top of the code:
app.display()
from guizero import App, Text
Your code should now look like worst2.py. Test
Create an app with a title: your app: the title text should flash, appearing and
disappearing once every second.
Martin app = App("it's all gone wrong")
MAKER

O’Hanlon title = Text(app, text="Some hard to read The wrong widget


text") Using an appropriate widget can be the difference
Martin works in between a great GUI and one which is completely
the learning team
app.display() unusable.
at the Raspberry
Pi Foundation, Which widget would you use to enter a date? A
where he creates Experiment by changing the colours, font, and TextBox? Multiple Combos? A TextBox would be
online courses, text size (see worst1.py listing). Our choices are more flexible but would require validation and
projects, and
learning resources.
not the best! formatting. Multiple Combos for year, month,
and day wouldn’t require validating but would be
@martinohanlon
app = App("it's all gone wrong", bg="dark
green")
title = Text(app, text="Some hard-to-
read text", size="14", font="Comic Sans",
color="green")

It’s important that text on a GUI also stays around


long enough to be read. It certainly shouldn’t
disappear or start flashing.
All widgets in guizero can be made invisible
(or visible again) using the hide() and show()
functions. Using the repeat function in guizero to
run a function every second, you can make your
text hide and show itself and appear to flash.
Figure 1 A slider to Figure 1
set date and time Create a function which will hide the text if it’s

100 May &June 2022 www.elektormagazine.com


slower to use.
Using a Slider to set a date and time (Figure 1),
worst1.py DOWNLOAD
as in the worst3.py code example, is not a great THE FULL CODE:
idea, though.
The Slider widget returns a number between 0
> Language: Python 3 magpi.cc/guizerocode
and 999,999,999. This is the number of seconds
since 1 January 1970. The function ctime() is used 001. # Imports ---------------
002.
to turn this number into a date and time. 003. from guizero import App, Text
Getting text from your user is simple: a TextBox 004.
or a multi-line TextBox should fulfil all your needs. 005.
006. # App -------------------
Is it too simple, though? Does this require too much 007.
typing? 008. app = App("it's all gone wrong", bg="dark green")
009.
What about the user who just wants to use a 010. title = Text(app, text="Hard to read", size="14", font="Comic
mouse? Perhaps a series of Combos each containing 011. Sans", color="green")
all the letters in the alphabet would be better 012.
013. app.display()
(Figure 2)? Start by importing the guizero widgets
and ascii_letters.

from guizero import App, Combo


from string import ascii_letters

ascii_letters is a list containing all the


‘printable’ ASCII characters which you can use as
the options for the Combo.
Create a single Combo which contains all the
letters and displays the app.

a_letter = Combo(app, options=" " + ascii_


letters, align="left")
Figure 2
app.display() Figure 2 Combos to choose letters

Your program should now resemble worst4.py.


Running it, you will see a single Combo which
contains all the letters plus a space and is aligned to
worst2.py
the left of the window.
To get a line of letters together, you could
> Language: Python 3
continually add Combo widgets to your app, e.g.:
001. # Imports ---------------
002.
a_letter = Combo(app, options=" " + ascii_ 003. from guizero import App, Text
letters, align="left") 004.
005.
b_letter = Combo(app, options=" " + ascii_
006. # Functions -------------
letters, align="left") 007.
c_letter = Combo(app, options=" " + ascii_ 008. def flash_text():
009. if title.visible:
letters, align="left") 010. title.hide()
011. else:
By aligning each Combo widget to the left, the 012. title.show()
013.
widgets are displayed next to each other against the 014.
left edge. 015. # App -------------------
016.
Alternatively, you could use a for loop, create a
017. app = App("it's all gone wrong", bg="dark green")
list of letters, and append each letter to the list, as 018.
shown in worst5.py. 019. title = Text(app, text="Hard to read", size="14", font="Comic
020. Sans", color="green")
Try both these approaches and see which you 021.
prefer. The for loop is more flexible as it allows you 022. app.repeat(1000, flash_text)
to create as many letters as you like. 023.
024. app.display()

Pop-ups
No terrible GUI would be complete without a pop-up

lektor May & June 2022 101


worst3.py Window widget
> Language: Python 3 Pop-up boxes can be used to ask users questions, but
they are really simple.
If you want to do show additional information or ask
001. # Imports ---------------
for supplementary data, you could use the Window
002.
003. from guizero import App, Slider, Text widget to create multiple windows.
004. from time import ctime Window is used in a similar way to App and has
005. many of the same functions.
006.
007. # Functions -------------
from guizero import App, Window
008.
009. def update_date():
010. the_date.value = ctime(date_slider.value) app = App("Main window")
011. window = Window(app, "2nd Window")
012.
013. # App ------------------- app.display()
014.
015. app = App("Set the date with the slider")
016. the_date = Text(app) You can control whether a Window is on screen using
017. date_slider = Slider(app, start=0, end=999999999, the show() and hide() methods.
018. command=update_date)
019. window.show()
020. app.display()
window.hide()

An app can be made to wait for a window to be closed


after it has been shown, by passing True to the wait
parameter of show. For example:

worst4.py window.show(wait=True)

You can find out more about how to use multiple


> Language: Python 3 windows in the guizero documentation:
lawsie.github.io/guizero/multiple_windows.
001. # Imports ---------------
002. from guizero import App, Combo
003. from string import ascii_letters
004.
005.
006. # App -------------------
007. box. guizero contains a number of pop-up boxes,
008. app = App("Enter your name") which can be used to let users know something
009.
010. a_letter = Combo(app, options=" " + ascii_letters, align="left") important or gather useful information. They can
011. also be used to irritate and annoy users!
012. app.display() First, create an application which pops up a
pointless box at the start to let you know the
application has started.

Figure 3 from guizero import App


Pointless pop-up

app = App(title="pointless pop-ups")

app.info("Application started", "Well done


you started the application")

app.display()

Running your application, you will see that an


‘info’ box appears (Figure 3). The first parameter
passed to info is the title of the window; the second
parameter is the message.
You can change the style of this simple pop-up by
using warn or error instead of info.
Figure 3 Pop-up boxes can also be used to get information

102 May &June 2022 www.elektormagazine.com


Figure 4

worst5.py
> Language: Python 3

001. # Imports --------------- Figure 4 Yes, we're sure!


002.
003. from guizero import App, Combo
004. from string import ascii_letters from the user. The simplest is a yesno which will ask
005. the user a question and get a True or False response.
006.
007. # App ------------------- This is useful if you want a user to confirm before
008. doing something, such as deleting a file. Perhaps not
009. app = App("Enter your name") every time that they press a button, though! Import
010.
011. name_letters = [] the PushButton widget into your application:
012. for count in range(10):
013. a_letter = Combo(app, options=" " + ascii_letters,
from guizero import App, PushButton
014. align="left")
015. name_letters.append(a_letter)
016. Create a function which uses the yesno pop-up to
017. app.display()
ask for confirmation.

def are_you_sure():
if app.yesno("Confirmation", "Are you
sure?"):
app.info("Thanks", "Button
05-worlds-worst-gui.py pressed")
else:
app.error("Ok", "Cancelling")
> Language: Python 3
Add the button to your GUI which calls the function
001. from guizero import App, PushButton
when it is pressed.
002.
003. def are_you_sure():
004. if app.yesno("Confirmation", "Are you sure?"): button = PushButton(app, command=are_you_
005. app.info("Thanks", "Button pressed")
006. else: sure)
007. app.error("Ok", "Cancelling")
008. Your code should now resemble 05-worlds-worst-
009. app = App(title="pointless pop-ups")
010. gui.py. When you run the application and press the
011. button = PushButton(app, command=are_you_sure) button, you will see a pop-up asking to you confirm
012.
with a Yes or No (Figure 4).
013. app.info("Application started", "Well done you started the
014. application") You can find out more about the pop-up boxes in
015. guizero at lawsie.github.io/guizero/alerts.
016. app.display()
How about combining all of these ‘features’ into
one great GUI?

Editor's note: This article originally appeared in MagPi magazine.


Create Graphical User Elektor publishes the Dutch, French, and German editions of MagPi.
Interfaces with Python
For further tutorials on how
to make your own GUIs with
guizero, take a look at our
book, Create Graphical User
Interfaces with Python. Its
156 pages are packed with
essential info and a range of
exciting projects.
magpi.cc/pythongui

lektor May & June 2022 103


background

Off-Grid Solar Systems


Electrical Energy Independent of the Mains Grid

By Dr. Thomas Scherer (Germany) low-power systems which can handle a peak looks very simple, but as ever the devil is
demand in the range of a few watts to a couple in the detail. In the following sections we
What is an off-grid solar of kilowatts. Also, as the levels of feed-in tariffs will therefore take a look at these individual
system? Where are such continue to fall, new and simplified designs components.
for fixed domestic solar installations that store  
installations necessary or the generated energy locally in rechargeable Here’s a real-life example: Klaus, a good friend
practical? What are the batteries solely for private use, rather than of mine, decided to install a 12 V system in his
most important design feeding into the public supply grid, begin to shed because of the low prices and manage-
make more sense. These installations typically able size of the components involved. To
considerations? These have a maximum nominal power output of a design the system and specify the compo-
questions and more will be few kWp (‘kilowatts peak’). Let us now look nents there are two questions that first need
answered in this article. at these small-scale systems in more detail. to be answered.

Principle of Operation Energy and Power


An off-grid solar installation requires at least The first question to answer is how much total
In the September/October 2021 edition three components: the solar panel itself; some energy needs to be stored by the system. This
of Elektor, we took a look at a photovoltaic energy storage in the form of a rechargeable directly affects the required capacity of the
system connected to the mains grid [1]. Here battery; and finally a charge controller that rechargeable battery and hence it is neces-
we will consider essentially autonomous solar ensures that the battery is not overcharged. sary to estimate the average load on the
installations that are isolated from the public For smaller systems, typically operating at installation. Bearing on this calculation is
grid. These can be used to generate electri- 12 V, that is in theory all that is needed. If, the number of cloudy days that the system
cal energy where otherwise a grid connec- however, a 230 V AC output is required at must be able to ‘survive’. Klaus would like to
tion would be too costly, such as in a shed 50 Hz or 60 Hz, a fourth component comes use an electric drill in his shed, and brew the
on an allotment, or impossible, such as on a into play: an inverter. Figure 1 shows a typical occasional cup of tea, but these relatively
motorboat or sailing boat. In general these are four-component solution: superficially it rare loads do not significantly affect the

104 May & June www.elektormagazine.com


average load calculation. More significant is The Rechargeable Battery or Batteries its input. This is an important consideration in
the requirement to keep cool beer always at The energy required to provide one day of selecting a battery. First we must decide on
hand: this calls for a 12 V refrigerator operating reserve power is at least 500 Wh. At a nominal the battery chemistry. A lithium battery pack
continuously with an average power draw of voltage of 12 V we will need a battery with a rated at 40 Ah can comfortably deal with this
20 W. The system should be able to run for capacity of at least 40 Ah. Since our inverter current (about ‘2C’, or twice the current that
at least one day without sun. is specified with an output power of 1 kW, we the battery can deliver for one hour) because
  must also keep in mind that at maximum load of its low internal resistance. However, such a
The second question is the peak power it will be drawing a current of at least 85 A at pack can easily cost over €250/US$280/£210
requirement. From this we can determine the
maximum current that will be drawn from the
rechargeable battery and hence also specify
the parameters of the charge controller (and
inverter, if used). Usually this question is very
easy to answer: in the case of my friend’s
allotment shed the answer was 1 kW, cover-
ing the power draw of the water heater, a
standard drill and possibly also a water pump,
all operating at 230 V.
 
The Solar Panel
Over a 24-hour period the refrigerator in Klaus’
shed will consume a maximum of 500 Wh.
Although he lives in a sunny part of south-
west Germany, the roof of his shed is unfortu-
nately in the shadow of a tree and so the panel
cannot be installed there. Instead it will have
to be mounted vertically on the south-fac-
ing wall of the shed, which reduces its power
output by some 30 % compared to mounting Figure 1: The standard wiring of the four components normally found in an off-grid solar
installation. The inverter on the right is only required if it is desired to run equipment
it at the optimal angle to the sun. The panel
designed for 230 V operation.
will therefore have to be over-specified by
some 40 % to compensate for this loss. Fortu-
nately there is plenty of space available and
the price of panels has fallen considerably in
recent years. An advantage of vertical mount-
ing is that in winter snow will not lie on the
panel, and moreover, since the sun is at a
lower angle, the output will increase: in the
best-case scenario the beer will be kept cool
even on sunny winter days.
 
Now we can calculate the required power
output from the panel. In this part of Germany
we can reckon on an total incident energy of
over 1200 kWh/m2 over the course of a year.
Over and above the expected daily energy use
we should allow a safety margin of 100 %, and
so for 500 Wh/day (from spring to autumn)
we should be looking to generate 1 kWh/day.
On the basis of 8 hours of sunshine per day
we arrive at a required power output from the
panel of around 125 Wp. On top of that we
add the compensation for vertical mounting
Figure 2: The 12 V solar panel mounted vertically on the wall of Klaus’ shed. It has an
and arrive at 175 Wp. That means we need a
output rating of 180 Wp.
180 W panel, which will fit comfortably on the
shed wall: see Figure 2.

lektor May & June 2022 105


and requires careful management. Instead,
Klaus plumped for a simple lead-based
battery costing a fraction of that price. An
obvious choice was a car battery, since these
are designed for high peak currents. However,
they have disadvantages: low efficiency, low
cycle life and high self-discharge rate. For that
reason he compromised on a gel battery: this
type does not like high discharge currents, and
so two batteries, each rated at 36 Ah, were
connected in parallel. This combination offers
a nominal 864 Wh of stored energy and cost
a little under €150/US$170/£130.
Figure 3: Three 12 V lead gel batteries, each rated at 36 Ah, are wired in parallel to act as  
energy storage in Klaus’ shed. In direct sunshine the selected solar panel
delivers so much power that it can easily fully
charge the batteries in a single day, and their
capacity is enough to cover 1.5 days without
sunshine. I had some misgivings about the
high current draw at the input of the inverter,
but Klaus decided to give it a shot and, if two
batteries proved not up to the job, to buy
another and add it in parallel. With the system
installed and the batteries fully charged, a first
test was fun using a 1 kW water heater. While
running the voltage at the battery terminals fell
to 11.7 V, but nevertheless it was easy enough
to bring half a litre of water to the boil. At a
rough estimate the efficiency of the battery
(output energy divided by input energy) at
these high currents is at most 50 % and the
current does not do the battery’s health any
favours. A further 36 Ah battery was there-
fore ordered and wired in: see Figure 3. Now
Figure 4: From left to right: light switch, 30 A electromagnetic circuit breaker, and MPPT
charge controller.
the initial terminal voltage when discharging
at 85 A is a more acceptable 12.6 V, and the
total capacity has been increased to nearly
1.3 kWh, guaranteeing over two days of reserve.
 
The Charge Controller
A search of eBay or of specialist distributors
will turn up a wide range of charge control-
lers. Controllers rated at 10 A go for as little
as €15/US$17/£13. However, a 180 Wp panel
will deliver up to 15 A at 12 V, and so we need
a controller rated at at least 20 A: these cost
around €20/US$23/£17. If the charge controller
is to be connected as shown in Figure 1, then
it is better to choose a 100 A version, costing
perhaps a little under €50/US$55/£45. Now
let’s go into the details.
 
The charge controller has the job of charging
Figure 5: Charge controllers that look like this one certainly do not have MPPT the battery using the power delivered from the
functionality (even if they carry a sticker bearing those letters!). (Source: United States panel, and terminating the charging process
Department of Energy)
when a threshold voltage is reached. This

106 May & June www.elektormagazine.com


ensures that the connected battery is not do this requires just a simple microcontroller
overcharged and hence damaged. Almost and a power MOSFET: a low-cost solution,
all charge controllers also control the load but not optimal.
connection and ensure that the load is  
disconnected when a lower voltage thresh- Now, the output power of a panel is given
old is reached, this time protecting the battery by the product of its output voltage and
from deep discharge. They invariably employ output current. For any given panel and
a microcontroller and so most can be config- level of illumination there is a point where
ured to work with different battery types, this product is maximized; almost invariably at
including lead-acid, lead gel and lithium this maximum power point the output voltage
chemistries. They also automatically adapt of the panel is above the battery voltage. An
to a nominal terminal voltage of either 12 V MPPT (maximum power point tracking)
or 24 V. Often it is also possible to configure controller continuously determines where
the undervoltage and overvoltage thresholds this ‘sweet spot’ is and drives a step-down
manually. voltage regulator circuit such that it draws
  the optimal current and delivers the maximum
The next consideration is the charger topol- possible output power. In the best case the
ogy. All low-cost examples use PWM control, output power from an MPPT controller can
even if it says ‘MPPT’ on the device: labels be 30% higher than that from a PWM control- Figure 6: This 1 kW inverter made by Ective has
proved very stable and reliable over time.
are cheap, but a ‘real’ MPPT charger is better, ler. However, this comes at a cost : even a
more complicated and therefore rather more low-cost MPPT controller will set you back
expensive. over €50/US$55/£45, and a name-brand
  unit will be at least €100/US$110/£85. The
In a PWM controller the charge current is 30 A charge controller shown in Figure 4 is The Inverter
adjusted so that the output voltage of the a low-cost MPPT type, and costs about €60/ If it is a requirement to generate a 230 V AC
panel is just above the current battery termi- US$70/£50, but Klaus felt that the extra output output, then an inverter is essential. Low-cost
nal voltage. The battery is therefore charged power was worth the money. If you are looking examples with implausible power specifica-
at the maximum possible current given the for an MPPT controller, avoid ones like that tions and output voltage waveforms at best
amount of incident light on the panel and its shown in Figure 5: this type is available in a distantly related to a sinusoid are best given
size, and the state of charge of the battery range of colours and with different markings. a wide berth. An important point to note is
over a wide range of conditions. The circuit to   that the specification for maximum continuous

Advertisement

PERFORMANCE. WE meet @ PCIM Europe


RELIABILITY. Hall 6, Booth 402

SERVICE.
Optocouplers by Würth Elektronik
With the new optocouplers, Würth Elektronik presents one of the latest additions
Optocouplers by Würth Elektronik to its optoelectronic product portfolio. The innovative design features a coplanar
structure and high-grade silicon for total internal reflection. The coplanar design
ensures the isolation gap stay fixed during the production process and provide
perfect isolation and protection for your application. The total internal reflection
provide stable CTR over the whole temperature range and high CTR even at low
current operation.

Provided in all industry standard packages. Available with all binnings ex stock.
Samples free of charge: www.we-online.com/optocoupler

• Innovative coplanar design • Stable CTR over whole


© eiPal

• High grade silicon encapsulation temperature range


• Copper leadframe for high reliability • High CTR in low current operation

lektor May & June 2022 107


power is given for an ohmic load. Klaus’ 1 kW
inverter is perfectly suitable for driving a 1 kW
500 ml water heater; but the situation with an
inductive or, less commonly, capacitive load
is completely different. In this case we must
also check the reactive power: note that the
apparent power is always at least as great as
the true power. Among the most problem-
atic devices are electric motors, which can
exhibit high inrush currents that will trigger
the built-in overload protection circuitry on an
inadequately-rated inverter. An allowance of
100 % when running motors is not excessive
Figure 7: In Klaus’ installation the inverter is connected directly to the rechargeable even for a high-quality inverter. Klaus’ 1 kW
battery, and the 12 V output of the charge controller is provided with extra protection.
inverter, shown in Figure 6, can comfortably
handle an electric drill and a water pump rated
at 450 W. It cost over €200/US$225/£170.
 
Wiring
As you may have surmised from the images so
far, the wiring between the solar panel, charge
controller, and battery is done using multi-
stranded wire with a 6 mm2 cross-section;
the connections to the 12 V cigarette lighter
sockets are not shown. The parallel connec-
tions between the batteries themselves are
made using 16 mm2 wire. The thicknesses
of wire used need to be appropriate for the
Figure 9: The foldable solar panel chosen by currents to be carried: this is not a good place
both Martin and Detlev can be stored below to try to save money.
Figure 8: LiFePO4 batteries under test before deck when underway. It is rated at 120 Wp.
 
installation in Martin’s boat. (Source: Martin (Source: Martin Jepkens)
Jepkens)
The inverter is connected directly to the
battery using 16 mm2 wire to minimize losses.
A direct connection is only possible when the
inverter (like the one here) offers undervoltage
protection, switching off to protect the battery
from deep discharge. The inverter is only
enabled when the 230 V output is actually
required: its quiescent current consumption,
in the tens of milliamps, would otherwise be
an unnecessary waste of energy. The final
set-up is thus as shown in Figure 7.

Other Off-Grid Systems


The electricity supply in Klaus’ shed is a typical
example of an off-grid solar installation. Various
suppliers offer ready-to-go packages compris-
ing a solar panel, charge controller and inverter,
with various nominal power levels. If you decide
to opt for wind energy rather than solar, then
again suitable generators and charge control-
lers are available based on broadly the same
principles. For my part, last year I modified my
robot lawn mower for autonomous power [2].
Figure 10: Guide to installing the charge controller in Detlev’s boat. This needed just a 50 W panel and a simple
PWM charge controller; no inverter was neces-

108 May & June www.elektormagazine.com


sary. Since then I upped the battery capacity inefficient, to run the engine frequently in is running. A 120 Wp foldable solar panel and
from 12 Ah to 30 Ah to help cover the periods order to charge the on-board battery, and so charge controller are also fitted for charging
of rainy weather we have had. I have also both have installed solar systems. when underway (see Figure 9).
recently replaced the PWM charge control-    
ler with a better (and more expensive) MPPT Now Martin is a smart engineer and doesn’t Because of the lack of available space, a fixed
controller, and the system can now generate need to rely on any advice from me. Never- solar panel installation is not a practical propo-
enough electricity to mow the lawn even late theless he discusses his ideas with me from sition on Detlev’s sportsboat. He therefore
into autumn. time to time. He was wondering whether the decided to use the same type of solar panel
  generator on his boat could be overloaded as Martin, although neither knew what the
There are of course many other applications if he happened to connect a huge 200 Ah other had chosen! Detlev is not an electronics
for off-grid power. Two of my other friends LiFePO4 battery across it. The dangers of specialist, and at first he wanted to use his
have boats: Martin navigates his large steel- such a course of action are explained in a extra 120 A on-board battery because it was
hulled boat through the riverscapes of the YouTube video [3]. Figure 8 shows how he still rather new. I did some calculations for
Netherlands, while Detlev makes mischief in set up his batteries for capacity testing: he him and advised him that using the cigarette
the Med in his sportsboat with a planing hull. decided on a battery with a LiFePO4 chemis- lighter socket on the ‘bridge’ of his vessel to
Both often spend days away from a harbour try mainly because of their long cycle life, but connect the solar panel was not a great idea
or other mooring where electricity is avail- also because of their compactness compared from a reliability point of view: I suggested
able and therefore would like to have more to lead-based batteries. In Martin’s boat the the use a a waterproof Neutrik connector
independence, especially as far as refrigera- on-board battery is separate from the starter instead. I pre-wired the connector and drew
tion is concerned: not in this instance just for battery. In order to ease the burden on the up an installation guide (Figure 10) for his
beer, but for other sustenance as well. It would alternator, the batteries are each charged via boatbuilder, so that the whole system could be
be ecologically unfriendly, not to mention their own charge controller when the engine set up in harbour in Istria. The combination of

Advertisement

Advanced ML for
every solution
Try free at edgeimpulse.com

lektor May & June 2022 109


most costly part of the system is the battery:
a 6.5 kWh LiFePO4 battery costs over €3000/
US$3400/£2600. With a guaranteed 6000
charging cycles at 90 % discharge depth that
means that around 36 MWh of energy will
have flowed via the battery, making the battery
cost around €0.09/US$0.10/£0.08 per kWh.
Furthermore, at that point the battery is still
not completely dead and so the effective cost
per kWh will be even lower. Over the life of the
battery a solution like this can save costs of
very roughly €13000/US$15000/£11000 using
energy one has generated locally. If an electric
vehicle is also charged (at a low charge rate)
then an installation of this kind can pay for
Figure 11: Semi-off-grid solar installation for a house. The three-phase current
measurement controls the inverter in such a way that no electrical energy is driven into itself within a few years.
the grid.  210644-01

Contributors
Text and figures (unless otherwise stated):
Dr. Thomas Scherer
foldable 120 Wp panel plus a Victron Energy battery, it also avoids a large amount of Editor: Jens Nickel
MPPT charge controller came to a total of bureaucracy: not a negligible consideration! Translation: Mark Owen
just under €500/US$550/£450. The charge (Note that such an arrangement may not be Layout: Harmen Heida
controller has a Bluetooth connection and legal in all countries.)
all parameters and graphs can be monitored  
using a smartphone app. In the arrangement in Figure 11 the savings Questions or Comments?
from using the simplified design add Feel free to send technical questions to
The Semi-Off-Grid House up to €1000/US$1150/£850 to €2000/ the Elektor editorial team by e-mail to
In these times of dwindling feed-in tariffs inter- US$2300/£1700. It would take a few years [email protected].
est has grown in a version of the fixed solar to make up for that using a feed-in tariff. The
installation that as far as possible dedicates
all of the generated energy to the demand of
the house. An array of, for example, 10 modern
solar panels will generate some 3.75 kWp; a
suitable MPPT solar charge controller could
then charge a LiFePO4 battery with a capac-
ity of say 6.5 kWh; and then a three-phase RELATED PRODUCTS
inverter could be controlled using a current
monitoring circuit (the three ammeters
towards the bottom right of Figure 11) to > PeakTech 4350 Clamp Meter (SKU 18161)
ensure that under no circumstances is any www.elektor.com/18161  
electrical energy driven into the grid. All the
‘current’ is therefore locally used. With electric- > Pokit Meter: Portable Multimeter, Oscilloscope and Logger (SKU 19854)
ity in Europe in 2022 costing around €0.35/ www.elektor.com/19854  
US$0.40/£0.30 per kWh this is a very attrac-
tive option: not only does it avoid having a > PeakTech 3445 True RMS Digital Multimeter with Bluetooth (SKU 18774)
complex and also expensive grid-tied inverter www.elektor.com/18774
with integrated charging electronics for the

WEB LINKS
[1] T. Scherer, “Balcony Power Plant,” Elektor Magazine September/October 2021: www.elektormagazine.com/210326-01
[2] T. Scherer, “Solar Power for Mowing Robots,” Elektor Magazine July/August 2021: www.elektormagazine.com/200553-01
[3] Victron Energy, “How to not blow up your alternator when charging lithium,” YouTube: www.youtube.com/watch?v=jgoIocPgOug

110 May & June www.elektormagazine.com


ethics

The 10-Year
Smartphone
Renew Your Expectations

By Priscilla Haring-Kuipers (The Netherlands)

What we expect from our devices drives what


we accept from our devices. We do not expect
a lot of time from our smartphone.

Maybe you’ve seen the ads online for a new What about your washing machine, your washing machine if it suddenly refused
smartphone that will last you 10 years. wake-up light, or your reflow oven? to spin cycle? I don’t think so. I think my
Maybe you too clicked on one, only to be   reflex would be to google the problem to
disappointed that this phone does not Giving you two to four years doesn’t seem see if maybe the internet knows that this
exist ... yet. The “10-year phone” is an so bad for most devices as you will proba- happens all the time and I should just
initiative that has been trying to get your bly want something new in this timeframe unclog the something-nozzle. Maintaining
attention, and the EU’s legislative atten- anyway. Which is a strange notion. Where and repairing it myself. Should that fail, I
tion, by tempting us with a future in which did this drive to continuously upgrade would probably get a repair professional
it becomes the norm for a smartphone to come from and isn’t it time we got ourselves IF the washing machine is not older than
last a decade. In order for this to actually rid of it? In light of our planet drowning 10 years.
work, there would have to be legislation on in our stuff, the resources and suffering
repairability, continued software support involved in making many of our devices Washing machines and smart phones are in
and availability of parts — especially the and our own appreciation of what we have. the same price range. But we don’t expect
battery. Information should be readily How about we adjust our devices and our our phones to last a decade. It’s time that
available on how to repair your phone mental models to last longer?  we smarten up.
yourself along with an official repairabil-
ity score [1]. New Reflex The 10-Year Smartphone is an initiative of the
My smartphone is now around five years European Right to Repair campaign, a coali-
Timing old, and I desperately need to have the tion of over 80 organisations from across
Somewhere along the journey of increas- battery replaced. It drops from 42% to Europe, pushing for longer-lasting and more
ingly amazing mobile phones, we appear dead in an instant. I found myself brows- repairable products.
to have accepted that these expensive ing for a new phone until I realised that I 210714-01
lifelines are only going to last two to four am still very happy with my phone beyond
years (in full working order). I guess we the suicidal battery. I am not alone in this WEB LINK
don’t often stop to consider how much new reflex; only 11% of people in the EU
[1] “10 Year Smartphone”:
time we actually expect from our devices. will repair their phone when it fails them.
https://10yearphone.com/
How long should your 4K flat screen last? Would I also immediately browse for a new

lektor May & June 2022 111


store
www.elektor.com

The Elektor Store


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

puhui T-962
Infrared Reflow Oven

Price: €229.00
Member Price: €206.10

www.elektor.com/20135

Raspberry Pi Zero 2 WH
(with pre-soldered GPIO Header)

Price: €34.95
Special Price: €29.95

www.elektor.com/20157

112 May & June 2022 www.elektormagazine.com


MakePython ESP32 Development Kit Arduino Uno Mini (Limited Edition)

Price: €74.95 Price: €54.95


Special Price: €64.95 Member Price: €49.46

www.elektor.com/20137 www.elektor.com/20098

Makerfabs 6 DOF Robot Arm Raspberry Pi Pico LoRa Expansion


with Raspberry Pi Pico + FREE Raspberry Pi Pico

Price: €139.95 Price: €64.95


Member Price: €125.96 Member Price: €58.46

www.elektor.com/20130 www.elektor.com/20096

lektor May & June 2022 113


Hexadoku
Puzzles with an Electronic Touch

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

SOLVE HEXADOKU AND WIN! PARTICIPATE!


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

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

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

114 May & June 2022 www.elektormagazine.com


Your design as a
Powerful Prototype
Order your first PCB at AISLER: it’s free up to €30

Beautiful Stellar Amazing


Boards Stencil Assembly

Order your PCB now


AND

WIN a Voltera V-One


Desktop PCB Printer
(valued at €4,150)
USE CODE
ELCCBBL
Valid until 30 June 2022

ORDER NOW!

www.elektormagazine.com/win-a-voltera-v-one
PROTEUS
DESIGN SUITE
Design Quality Assurance
Constraint Driven
Design
Flexible and scalable
Zone Inspector
rule system
Full support for design Analyze plane coverage and
rule rooms stitching
Manufacturing Grid view of plane
solder mask rules configurations
Live display of
Edit plane settings and
violation areas
draw order

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

[email protected]
+44 (0)1756 753440

You might also like