Elektor Electronics 2021-01 02 USA
Elektor Electronics 2021-01 02 USA
Elektor Electronics 2021-01 02 USA
95
JANUARY/FEBRUARY 2021
505 ELEKTORMAGAZINE.COM
MTheCam
Simple Mini Camera
p. 8
In this edition
I2S Test Signal Generator
with AVR Microcontroller
New LCR Meter - Part 2
Sensor Network with RPi and RF24
My Project: Homebrew CPUs
Connect Your Thermostat
with ESPHome
Error Analysis
Control Your Home with RPi
electronica Fast Forward
2020 Winners
Data Analysis and Artificial
Intelligence in Python
By our Partner Elettronica Open Source
www.elektor.com
www.elektormagazine.com
Labs Project:
2
I S Test Signal
Generator with AVR
Microcontroller
22
Next Edition
Elektor Magazine Edition 2/2021 (March & April)
Elektor’s friends at SparkFun Electronics are guest editing the next
edition of Elektor Mag! We are excited to announce that our editorial
and engineering teams are currently collaborating closely with engi-
neers at SparkFun Electronics — a Colorado-USA based innovator of
fun and interesting electronics kits and modules — on various amaz-
ing electronics projects, articles, and engineering tutorials for the
March/April edition. Below are just some of the articles and topics
that we are working on:
RPi Snoops on
433.92 MHz 27 >
>
>
Getting Started with MicroMod
Tips for Creating Custom Electronic Products
How to Build a DIY GNSS Reference Station
> Programming an FPGA
> DIY Circuit Board Organization
> Must-Haves for Your Electronics Workspace
> ClockClock: An FPGA Demo Project
> Implementing FreeRTOS on RED-V
44 Connect Your Thermostat with ESPHome
An Attempt at Doing Home Automation the Right Way And much more!
56 Raspberry Pi Full Stack Don’t miss the upcoming special edition of Elektor Mag created by
RPi and RF24 at the Heart of a Sensor Network engineers and makers from Europe and America!
66 Multi-Channel Power Analyzer
Up to 3 Channels, with Graphic and Alphanumeric Display
Elektor Magazine edition 2/2021 (March & April) will be published
86 New LCR Meter 50 Hz - 2 MHz (Part 2) in March 2021. Arrival of printed copies for Elektor Gold Members is
Operation, Calibration, and Firmware Programming subject to transport. Contents and article titles subject to change.
DIY LiPo
Supercharger Bundle
GreatScott and Elektor’s LiPo Charger, Booster,
and Protector
Need a rechargeable LiPo power supply for 5- and 12-V output? Want to practice SMD
soldering? You can with a little help from GreatScott! (a YouTuber with 1+ million
subscribers) and Elektor. In this article, we detail both the handy portable power supply and
the obstacles we encountered during the development process.
For experimenting with electronics we are used to our trusty power GreatScott! [2] has sketched the raw schematic of a LiPo powered,
supplies on a lab bench. While this is the usual way to get prototypes rechargeable supply that shall be user buildable with SMD compo-
up and running the leads sometimes become a bit of a handicap if nents. All the components and ingredients look not that complicated
the device we build is meant to be portable or moving around the lab. on first sight, a charging IC for LiPo batteries, a DC/DC converter
The workaround can be a bunch of batteries carefully crafted with to provide 5 V and 12 V and a battery protection IC. All components
duct tape, hot glue and some cheap DC/DC converter into a kind are chosen to be 1206 in size where possible, to allow even begin-
of portable battery pack. That works for a prototype, but it isn’t that ners to get all SMD components onto the PCB and hopefully show
nice, especially if you need 5 or 12 V for your device. This can be done that soldering SMD is not a kind of black magic that only well trained
in a better way and it has. After meeting at the 2019 productronica wizards can do. Parts that need some kind of special attention are
fair in Munich, Elektor and popular engineer GreatScott! decided to already built onto the PCB to make your start into SMD assembly even
team up to develop a handy DIY kit just for you. a bit easier and avoid dealing with small pins and pads underneath
ICs. For charging you can use direct attached cables providing 5 V
Who is GreatScott? Great Scott! is the name of a Youtube channel [1] or use the USB-C connector on the add-on PCB to provide power
launched back in 2013 presenting electronic projects and knowledge to recharge the battery. With USB-C it is a lot easier to connect the
to more than 1 million subscribers. The videos include a wide variety of plug in the right orientation and the connector on the PCB itself is
DIY projects that viewers can recreate. Many other videos offer inspi- held in place by four THT mounting holes for more stability. Besides
ration and clear solutions to engineering problems. As a few videos using the power supply a fun part of the project is building it in the
have already launched featuring Elektor products, the idea came up first place. And this comes with a nice step by step guide included in
to present a DIY kit that everyone that is interested can use to expend the package. Refer to Figure 1 for a first look.
their knowledge and skills.
SPECIFICATIONS
Input: 5 V +/– 10%
Output: 5 V / 1.5 A or 12 V /0.75 A
Single Cell Lithium battery
The three ICs that make the board work are from a well-known vendor.
The battery protection IC is a XB8089D from Xysemi, a chip only
found at distributors that specialize in Chinese silicon products. This
chip handles overcharge , over discharge, over current and reverse
polarity protection in a small SOP8 package with expose pad for a Figure 4: PCB in action.
reasonable price. While many batteries used in products like drones
have integrated protection, it won’t be safe to remove the chip from
the circuit if a lithium battery without protection is installed.
The chosen BQ24092 comes from a BQ2409x line and this is where
With the sketches and rough schematic GreatScott provided, Elektor you need to check the datasheet carefully. Depending on the chip
added their experience in creating and designing PCBs. You might chosen the mentioned resistor needs to be 10 k or 100 k, and it was
think this is the end of the story (you have a PCB and everything is easier to change the resistor than the whole charger IC. There are more
fine), but as rule of thumb, it usually takes three iterations, as you can lessons learned as we did three iterations. How to fix the disintegrat-
see at Figure 2. The first prototype worked almost as expected besides ing DC/DC converter is something that is quite simple if you know
a few minor issues, like not charging the battery or disintegrating the what parts you can choose. Also some do’s and don’ts were made
DC/DC converter if load exceeded a certain point. The battery protec- during the iterations and for manufacturing we may have also a few
tion IC will prevent the lithium battery form becoming damaged ( sort lessons learned you can benefit from. Meanwhile you can check out
of ) but the current limit is at 10 A ( meaning 37 W ), so the DC/DC the Youtube channel of GreatScott! and see the assembly and the
converter disintegrated at around 15W. And the charging, that was power supply in action. Details and an in-depth description of the
an easy fix, as there was somewhere a typo, making the desired 10 k circuitry will follow next time. The rough specifications are presented
resistor a 100k resistor, it was just a short swap of components. But in the nearby textbox. The final revision of the PCB looks like what
to be honest, we know where to look when it comes to the wrong you see in Figure 3. Figure 4 shows it in action..
resistor for charging as we have seen this in other projects before. 191188-01
WEB LINKS
[1] GreatScott! Youtube channel: www.youtube.com/c/greatscottlab/
[2] GreatScott interview: www.elektormagazine.com/news/elektor-magazine-2020-summer-edition
MTheCam
A Simple Mini Thermal Camera
Did you blow the candle out? And was the hob turned off? Everyone has, at some point,
experienced that nagging feeling after leaving the house that some heat source or other
might still be on and poised to do untold damage. Now you can find out using MTheCam
and your smartphone. The project described here is based on an eight-by-eight pixel thermal
sensor from Panasonic that, naturally, has many other applications.
When we say ‘hot spot’ we are, of course, not referring to public Internet components will
access points. Instead we are referring to locations that are significantly often give an early
warmer than their surrounding environment (and the opposite for ‘cold indication of their
spots’). They can be symptomatic of a fire, overheating components imminent demise
or short circuits, thermal bridges, or broken seals allowing heat to by becoming
escape. If they are not accompanied by a naked flame or glow then hotter than usual;
they are invisible to humans. To track them down the eye needs some and, in machinery,
assistance: enter MTheCam. worn bearings and inadequately lubricated
surfaces will heat up, giving a timely warning that can help extend
Tracking down hot spots means much more than detecting a hotplate the life of the equipment. Even people can be detected, tracked and
that has inadvertently been left on. In electronic circuits, overloaded counted using a heat sensor.
As well as instruments that measure temperature by direct contact attractive, it also makes it easier to recognise objects in the image. The
there are also contactless sensors that measure infrared radiation range of the false colour gradient is also extended somewhat beyond
from objects, thus determining the average temperature in the field of the minimum and maximum temperature values, acting like a magni-
view. This is done by using the pyroelectric effect where the electrical fying glass over the temperature readings (Figure 2).
potential of electrodes in a polarised crystal change when exposed
to thermal radiation. This effect can be exploited using electronics [1]. The AMG88xx thermal sensor
To capture thermal images, Panasonic has developed a powerful
The project thermal MEMS (Figure 3) available in two variants covering different
MTheCam takes measurements up to five times per second simul- temperature ranges. The very tiny package includes the optics, the
taneously from 64 points arranged in eight rows of eight columns. thermoelectric transducers, analogue-to-digital conversion and signal
Similar to an ordinary camera, these are arranged to have a 60° field conditioning [3]. The AMG8853 covers the range from 0°C to 80°C
of view. Each point can detect a temperature between 0°C and 80°C while the AMG8854 covers –20°C to +100°C, with maximum error
(or alternatively from –20°C to +100°C). The individual readings are specifications of ±2.5 K and ±3 K respectively. Both are accessed
displayed using a gradient of colour values, resulting in an image with over an I2C bus. The absolute accuracy is not outstanding, but the
very low resolution. This image can be served as a web page over device is nevertheless perfectly good for qualitative assessment of
a wireless network so that it can be displayed on a smartphone, for relative values.
example. The gaudy but chunky image is certainly not reminiscent
of HDTV but it does clearly display hot and cold spots in contrast- With a couple of lines of software it is possible to calibrate the readings
ing colours that distinguish them from surrounding objects. As well from the device that increase the accuracy of the results and reduce
as this false-colour image, the temperature of each pixel is shown in noise. The sensor is available in a space-saving SMD package that is
degrees Celsius, allowing for a more precise analysis (see Figure 1). designed for reflow soldering. For our application we use it mounted on
a small, home-made breakout board that also includes a few passive
Furthermore, the 64 readings can also be requested in JSON format, components (in easily hand-solderable 0805 packages) required for
making it easy to share the information with other applications. decoupling the power supply and pulling up the I2C bus lines. Pads on
the edge of the board carry the +5 V and GND power supply pins as
A little bit of mathematics lets us give the illusion of a higher resolu- well as the three signal lines required (INT and the I2C bus). This allows
tion than provided the 8-by-8 pixel matrix. Bicubic interpolation [2] is a straight or right-angled pin header to be fitted. Figure 4 shows the
used to create a ‘fake’ 32-by-32 pixel image that not only looks more circuit diagram of the breakout board and, for interest’s sake, a little
R1 R2 R3
C4
3k3
3k3
3k3
1
1 IC1 8 16V
NC NC
J1
SDA
1 2 Sensor element 9
GND I 2C I/F ROM VPP
2
EXT_VDD Selector
3 3 Control 10
GPIO26 DVDD-PC
4 SCL
GPIO36
5 4 INT Gain 11
GPIO0 ADC amp
NC
6
VBAT_Li_Ion
7 5 AD_SELECT 12
VESP_3V3 AVDD-PC
8 Thermistor
VBUS_VIN
6 13
GND VDD
To M5Stick-C AMG8853
expansion 7 14 C2
NC NC
connector
1
16V
R4
C3 C1
20
1 5 1
16V 16V
180337-10
Figure 4: Circuit of the AMG88xx sensor breakout board showing its internal architecture.
of the internal circuitry of the sensor. The free download accompa- For our project we need only the ESP32, the display and the recharge-
nying this project [9] includes layouts of the two layers of the board able battery. The other features are still there, of course, and will no
and the component-mounting plan. Those in search of an easy life doubt find a use in other applications.
can purchase a ready-made module from the author.
The display on the M5StickC is small but it shows a sharp and colourful
M5StickC, the Jack of all trades image. User interface designers will be challenged to display informa-
Any smartphone with a WiFi interface and a touch screen for input tion within the small area available. The thermal sensor image works
and output makes a perfect user interface for MTheCam. In order to well on the display and we have a couple of lines available to show
use the WiFi interface to communicate with the sensor we equip it readings as text. The display driver library allows plenty of scope for
with a ‘smart’ data transmitter comprising of an SoC (system on a fancy graphics, animations and festivals of light and colour: let your
chip) with a microcontroller and a WiFi peripheral. imagination run riot!
We decided to use an Espressif ESP32 [4]. This module includes every- The 80 mAh lithium-ion battery can power the M5StickC running flat
thing a developer’s heart could wish for and it is inexpensive and out for around an hour. It is charged over a USB-C connector at 5 V
power-efficient. Moreover, it supported by the Arduino ecosystem. The and 500 mA using the cable supplied connected to a standard USB-A
only electronics needed besides the sensor and the ESP module is a socket. A small button on the side turns the device on, while holding
5 V power supply, either from USB or, for mobile use, from a recharge- the button down for six seconds turns it off.
able battery. Looking in the Elektor Store our eyes fell upon a product
in a dazzling shade of orange that includes an ESP32 and some other Cooperation
interesting components, the M5StickC [5], which is perfect for the job. The sensor breakout board is plugged into the external expansion
connector. It can be connected either flat on its back using a right-an-
The M5StickC crams rather a lot into its tiny 50 mm by 26 mm by 14 mm gled header, or using a straight header to make measurements along
enclosure. It contains an ESP32-Pico with 4 MB of flash and 520 kB of an axis parallel to the longest edge of the device. This allows it to be
SRAM, an 80-by-160 pixel 0.96 inch display, a six-axis motion sensor, ‘fired’ at its target (Figure 6). Any 3D-printing wizard should be able
a real-time clock, a power management unit, a red LED, an infrared to quickly whip up a neat enclosure for either configuration.
LED to allow it to be used as a remote control, a MEMS microphone,
an 80 mAh rechargeable battery, a USB-C port, a Grove connector The M5StickC expansion connector has eight connections. We only
(power, ground and two I2C ports) and an 8-way header with three use the 5 V output, ground, the two I2C pins carrying data and clock
ports and power supply — enough to make even the most jaded signals (SDA on GPIO26 and SCL on GPIO0), and the INT inter-
engineer sit up and pay attention! rupt signal that we connect to GPIO36. The BAT, 3V3 and 5 V input
connections are unused. Note that GPIO36 can only be used as an
The small dimensions, display and rechargeable power source mean input, a little piece of information that might save you a while in track-
that the M5StickC can be used as a rather natty smart watch, for which ing down any problems.
a suitably garish strap and mount is included. It certainly makes a
fashion statement as Figure 5 shows! Who needs the boring products Currently, the interrupt feature is not implemented in the software. The
of a certain Californian fruit company to which you can’t even plug sensor chip is able to generate an INT signal when a specified minimum
anything in? or maximum temperature threshold is exceeded. In fact, this can be
A matter of software
To create the firmware it is possible to use either Espressif’s proprietary
development environment or the Arduino ecosystem. The latter is very
easy to use as there is a highly-effective global community support
network. The original Arduino IDE is a good way to get started, but
it is not really up to the task of building more advanced applications.
Instead, the author recommends the free Visual Studio Code editor
from Microsoft that supports Arduino via an extension [6]. M5Stick-C Figure 5: The M5StickC as a bright orange smartwatch. (Source: m5stack.
(esp32) can be found under the Board Manager. com)
The firmware for MTheCam was developed by the author using C++.
Besides the Arduino source code MTheCam_LT.ino and a couple of
.h and .cpp files (Mxxx.cpp/h) we also use the highly-recommended
ArduinoJson library for JSON handling (version 6 of this library is
required; version 5 will not work). The hardware of the platform are
comfortably supported by the M5StickC library [8]. This must be
installed using the library manager (F1 – Arduino: Library Manager).
While the ArduinoJson library documentation is a pleasure to read, this
cannot be said of the descriptions of the M5StickC library. To use it
successfully requires the source code to be tediously and painstakingly
examined and is rather too much like work and not enough like play!
We will now look at various snippets of code covering the various
functions in their logical sequence.
Sensor read
Readings are made available in byte-wide registers in the sensor ten
times per second. The software continuously reads these registers
over the I2C bus using the Wire library. The pixel data has a resolution
of 12 bits and so two bytes are used for each. Thus the code to read
the registers in MTC_readReg() appears as follows. Figure 6: Right-angled or straight — there are two ways the sensor can be
mounted on the M5StickC.
#define BUF_LENRX 128
int reg = 0x80;
byte _rxBuf[BUF_LENRX];
. . .
Wire.beginTransmission(devAddr); // chip address: see a degree Celsius. This means a temperature of 21.35°C is represented
datasheet as 2135. The sensor is initialised so that, internally, it performs a moving
Wire.write(reg); // 0x80 -> read 128bytes of 64 average of two consecutive frames, thus yielding a significant amount
pixels @ 12bits of noise reduction. The registers are read out in a single pass that
Wire.endTransmission();
guarantees all the values belong to the same frame. The calculations for
if (Wire.readTransmission(devAddr, rxBuf, BUF_
the pixel temperature and the on-chip thermistor temperature (which
LENRX) == I2C_ERROR_OK) { success = true; }
we do not use here) differ (see the datasheet [3] for more details). For
Wire.endTransmission();
improved accuracy in the calculation, intermediate values are repre-
Under some circumstances, Wire.readTransmission() can return sented in units of 1/10,000 of a degree, with a subsequent division
an error code that can come in useful when tracking down bugs in by 100 to produce final results represented in hundredths of a degree.
the read process.
Calculating the colour value
The code excerpt shown in Listing 1 is responsible for reading the The colour display is implemented using the HSL colour model [10]
sensor and calculating temperature values. With the help of a little (Figure 7) and the M5StickC bundle includes a suitable TFT driver
bit-twiddling, two entries in the rxBuf[] array are converted into a library. Of the three parameters hue (H), saturation (S) and luminance (L)
temperature represented as an integer in units of one-hundredth of we only vary the H parameter, or angle, in the colour wheel. The S
connect the M5StickC to a wireless network and set it up as a web server. excerpts from the WiFi and web server code are given in Listing 3.
MTheCam can display colourful thermal images on any smartphone.
The Arduino software includes the libraries WiFi.h and WifiClient.h
that implement just such a web server. All it needs as parameters are HTML and JSON
the access details for the network’s SSID and password. After reset, or Request for the pages / and /index.html generate a web page
a power cycle, the display will show that the device is trying to connect with an eight-by-eight grid of colour patches with the temperature
to the network. If this is successful it will show the IP address to which values superimposed on them. The page also contains the minimum,
it has been assigned. If unsuccessful, it is necessary to verify that the maximum and average temperature values (tmin, tmax and tavg
access details are correct and that the access point is in range. The respectively) over the frame. Different colours represent different
range of the device is surprisingly good and it can certainly hold its temperatures over the range tminrange to tmaxrange, with these
own against smartphones in this respect. limits computed dynamically as described above. The ‘Image’ button
switches the display to a ‘high-resolution’ false colour mode with
The web server then sits waiting for requests on the local IP address interpolated values, and the ‘Values’ button returns to the original
assigned to it by the router for the pages /, /index.html and /frame. mode. By default a new image is displayed every second. This period
For example, it might respond to http://192.168.10.1/. can be adjusted using a slider. The ‘Grid’ check box overlays a grid
on the image.
Once we have set up the WiFi connection we need to tell the web
server what to do when it receives a request from a client browser. A A request for the page /frame delivers the temperature values in
corresponding function will be called so that, for example, a request for JSON format so that they can be processed further by another appli-
/ (or equivalently for /index.html) will result in a call to MW_index() cation. It is best to leave at least a 200 ms delay between requests as
that, in turn, delivers a document to the client: the sensor chip requires around 100 ms to take a set of readings. If
push had come to shove the JSON object could have been created
webServer.send_P(200, “text/html”, _uidoc); using ordinary string manipulation functions, but there is a very
convenient library called ArduinoJson.h that makes things much
send_P is used because the HTML document _uidoc is stored in the neater. This library can also read JSON objects. A typical object
flash memory as PROGMEM in order to reduce RAM usage. Commented might appear as follows.
RELATED PRODUCTS
> M5StickC
www.elektor.com/m5stack-m5stickc-esp32-pico-mini-iot-development-board
WEB LINKS
[1] Pyrometer: https://en.wikipedia.org/wiki/Pyrometer
[2] Interpolation in images: https://en.wikipedia.org/wiki/Image_scaling
[3] AMG88xx: https://bit.ly/2VPiCGc
[4] ESP32 documentation: https://bit.ly/37FlcEk
[5] M5StickC: https://bit.ly/2In5aq9
[6] Visual Studio: https://code.visualstudio.com/
[7] ArduinoJSON : https://arduinojson.org/
[8] M5StickC library: https://github.com/m5stack/M5StickC
[9] Author’s project page: https://www.micom.de/lab/mthecam
[10] HSL colour model: https://en.wikipedia.org/wiki/HSL_and_HSV
Weller WE 1010
Soldering Station
By Harry Baggen (Elektor)
The choice of
soldering irons
and soldering
stations is enormous
but, for many electronics
enthusiasts, the name Weller
will immediately spring to
mind. Weller’s soldering
stations are widely used
and the prices are not
bad. In this review we look at the cheapest soldering station in the professional series,
the WE 1010. With its price of just over €150/£130/$170, this station is also of interest to
the serious hobbyist.
Purchased The display shows the current temperature of the soldering tip in
So the decision fell for the WE 1010 consisting of a base station with large digits and below that the set target value in smaller digits.
LCD display and a soldering iron with a power of 70 W. Although In addition to the target value, a heating symbol appears when
this is a soldering iron with passive temperature control (heating the iron is heating up. Even when the standby function is active
and sensor are not in the tip itself but behind it) I don’t think it is or when the lock-out function is used, the corresponding symbols
an issue (more on this later). The box contains a base station with are still displayed.
matching power cord, a WEP 70 soldering iron, a fairly simple stand
consisting of a moulded base with a holder that is inserted into it, Due to its weight the soldering iron holder stands well on the table.
and a sponge. It all looks rather ordinary but everything is neatly It has a number of holes to accommodate spare tips. To wipe the
finished. On the station there is an on/off button, an LCD and some tip clean there is, of course, the customary yellow sponge. There
control buttons (Figure 2). is no room for brass wool or the like. If you prefer using such a
bundle of metal wool to wipe the tip you’ll have to buy an extra
Unfortunately, the display is not backlit. However, it is very clear container with metal wool.
and easy to read, even with little ambient light. Alas the power
switch has no built-in lighting either. Thus you can only see that The soldering iron itself is quite slim and the flexible cable is nice
the station is on because something is visible on the display and and long. It is also so flexible that you hardly notice it when solder-
the power switch, in the on position, shows a red line. ing. The soldering tips can be changed simply by unscrewing the
metal sleeve of the front part using a plastic nut (Figure 3). It is
The base station is quite heavy (almost 2 kg) and feels solid. The because the tip is indirectly heated, as already mentioned, that
1.5 m long cord (with silicone sheath) on the soldering iron is very replacement tips are very inexpensive — even the original
supple and it lies well in the hand with its covering of a kind of ones from Weller. They are available almost everywhere
pressed foam. The cable of the soldering iron has a 5-pole plug at and I have already bought some with other tip
the end which is inserted into the socket on the base station, then shapes (Figure 4).
locked by turning. The metal part of the soldering iron is connected
to the earthed socket of the mains cable. There is no separate earth Lighting up!
connection on the station. After switching on it took around 35 seconds until the soldering
tip had reached a temperature of 350°C. The 380°C needed for
Operation and use lead-free solder needed around 5 seconds more. Soldering with
The operation of the soldering station is kept very simple. With the WE P70 soldering iron works smoothly. There are no problems
the up and down buttons the temperature can be set higher or when soldering average components and standard copper pads.
lower. On delivery it is preset to 350°C. There is also a menu key With large soldering surfaces you will notice that the temperature
with which you can access the following settings: standby time, drops a bit and the tip needs a few seconds to reach the set point
the time after which the soldering iron is switched back to a lower again (an active soldering iron reacts much faster in such cases),
temperature (max. 99 minutes); offset, for temperature correc- but this only takes a short time thanks to its 70 W heating power.
tion and only useful if you can measure the temperature of the tip In such cases it is advisable to use a short soldering tip with a large,
(max. ±40°C); switching between °C and °F; and finally the abilty bevelled tip so that the heat can be transferred more optimally.
to set a lock code. The tip supplied is rather too narrow for this and is better suited
to soldering small components. a lot to me. And the standby function? It’s not ideal, but you
To implement the standby function the station monitors how can live with it. In spite of these minor shortcomings I would
much heat is supplied to the iron rather than using a motion definitely buy the WE 1010 again as it is a quality soldering
detector in the soldering iron. If the heat output remains steady station at this price point.
for a certain time (standby setting), the temperature is automat- 200572-04
ically reduced to 180°C (Figure 5).
The tip temperature is automatically raised again if a lot of heat is
removed from the tip, such as by sliding it over
the wet sponge. A more direct method is to
briefly press one of the buttons on the
base station. For me the longer
standby times are better and
Questions or Comments?
Do you have questions or comments about this article?
Contact Elektor at editor@elektor.com.
30 minutes is just right. Alternatively, you can switch the standby
mode off completely. So far I have not noticed any scaling of the
tips. Should this ever happen, the tips are inexpensive enough to
Contributors
replace.
Text: Harry Baggen Editing: Eric Bogers
Conclusion Photos: Patrick Wielders Layout: Giel Dols
I am very satisfied with the WE 1010 as the successor to my old
Weller soldering station. The soldering iron lies comfortably
in the hand and the soldering is good. The adjustment options
on the base station are limited, but sufficient for normal use. RELATED PRODUCTS
What I am missing is a better optical power-on indicator, as
you have to look at the display or search for the red line on the
> Weller WE 1010 Digital Soldering Station (70 W)
power switch. Would an illuminated power switch or an extra www.elektor.com/18513
LED really have cost that much more? It would have been worth
WINNERS
2nd 3rd
21
20
S1 IC1
7
1 VCC
Tags 0
AREF
AVCC
VCC
EF 12 2
D 3 23
Digital audio, Raspberry Pi, DAC, I 2S C
B
4 4
5 24
PC0
ATmega328P-20PU 10
IC2
10 IC5B
A 6 8 PC1 SER
Level 98 7
C
25
26
PC2 PD0
2
3
11
12
A
12
11
D
S
Q
9
PC3 PD1 B CLK
entry level – intermediate level – expert level 27
PC4 PD2
4 13
C Q
8
VCC 28 5 14 R
Time R3
10k
1
PC5
PC6/RESET
PD3
PD4
6 3
D
E
13
IC5A
About 4 hours PD5
11 4
F
4
CLK 14 12 5
PB0/CLKO PD6 G
Tools 15
PB1 PD7
13 6
H QH
9 2
D
S
Q
5 SDATA
32bit
16 2 7 3
Soldering tools (through-hole), AVRISP K1 17
PB2
15
CLK QH CLK
6
PB3/MOSI INH Q
2 1 18 1 R
Cost 4 3 19
PB4/MISO SH/LD
1
PB5/SCK 74HC165 IC4D
Approx. €15 6 5 12
GND
GND
PB7
PB6
11 SCLK
13 =1
ISP VCC 12.288MHz
IC4B
8
10
9
22
C3 4
6
C1 C2 = 15 C4 R4
100n 22p X1 22p
150R
Since its introduction in 1986, the Inter- R1 R2 12.288MHz IC3 22p
100R
11 9
2k2
RESET Q1 VCC
Integrated Circuit Sound (I2S) bus has been 9
IC4C
Q2
7
IC4A
VCC 8 CLK 10 6 1
the “de facto” standard for transmission of serial LED1 S2 10 =1 CLK Q3
Q4
5 2 =1
3 IC4=74HC86
IC5=74HC74
3
digital audio signals. During the development Reset Q5
2 LRCLK
Q6
and test of our “Audio DAC for the Raspberry VCC
Q7
4 192kHz
K2
13
Q8 SDATA
Pi” [1], we came up with the idea to design a K3 Q9
12
SCLK
SD
16 16 14 14 C5 C6 C7 C8 C9 14 SC
dedicated circuit that generates an I2S signal IC2 IC3 IC4 IC5
Q10
Q11
15
LRCLK
LR
8 8 7 7 100n 100n 100n 100n 100n 1
to test the DAC without connecting the RPi as 3V3..5V Q12
I2S
Design options
To build an I2S test signal generator, one
option would be to use a 24-bit ADC with It would be obvious to use a microcontroller The serial clock (SCK or SCLK) must be
I2S outputs, with a signal (sine wave) genera- that supports I2S for this task, but why not 12.288 MHz (2 channels * 192 kHz * 32 bit).
tor as input. But to check if the analog output use a very common microcontroller like the Since the maximum clock frequency of the
signals of the DAC are indeed flawless, the ATmega328P instead? The problem of course microcontroller is 20 MHz, the only way to
sine wave in the I2S signal must be perfect is that it doesn’t support I2S. It was quite a output serial data (SD or SDATA) faster is
to perform proper distortion measurements. challenge to build a digital sine wave genera- to use an external parallel-in serial-out shift
The test signal should not be degraded by tor with I2S output using this microcontroller register and use the clock of the microcon-
an inferior analog source or ADC in any way. and some additional hardware, but this project troller to clock the shift register. PB0 must
shows that it can be done! The firmware of be configured as CLKO (Clock Out) when
As an alternative, a microcontroller can be the ATmega is developed in BASCOM-AVR. programming the fuses of the ATmega328.
used to generate the I2S signal, using a table The complete schematics of the signal gener-
with 32-bit samples that can be accurately Some extra hardware is needed ator can be seen in Figure 1. Apart from the
calculated to ensure the quality of the audio The goal is to create an I2S signal with 32-bit shift register a ripple counter, a flipflop and
data. This will generate a signal that is perfect data at a sample rate of 192 kHz, which is some Exclusive-ORs are added to free the
for distortion measurements, in this case a close to the maximum sample frequency of microcontroller from other (timing) tasks than
1 kHz sine wave with 192 kHz sample rate. the PCM1794A used in our RPi audio DAC. just outputting the bytes of the samples.
HC4040 RESET
window port D
74HC74 SDATA 7 clock cycles 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25
3 zero-bytes + extra NOPs before Do-Loop to start MSB-byte at correct moment
HC165 QH bits 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
HC165 CLOCK
HC165 LOAD with exor's from Q4
1st byte (MS) 2nd byte 3rd byte 4th byte (LS) 1st byte (MS)
HC4040 CLOCK
Q1
Q2
Q3
Q4
Q5
Q6 LRCLK (fs)
WEB LINKS
[1] Audio DAC for Raspberry Pi: www.elektormagazine.com/labs/audio-dac-for-rpi-networked-audio-player-using-volumio
[2] Downloads gerber files and software: www.elektormagazine.com/200253-01
[3] This project’s Elektor Labs page: www.elektormagazine.com/labs/32-bit-i2s-sine-wave-generator-200253
In the DIY community (at least in Europe where I’m living), 433.92 MHz protocols
433.92 MHz will ring a bell. Many cheap wireless devices such as Devices that are using the 433.92 MHz frequency operate in the
garage door openers, weather sensors, and doorbells are using this unlicensed industrial, scientific, and medical (ISM) frequency
frequency. Moreover, the hardware to communicate with these band. But the frequency is one thing, the protocol they’re using
devices is equally cheap. is another one. There’s no standard protocol for this frequency.
This is no Z-Wave or Zigbee. However, many protocols of these
The disadvantage is that most of these devices use plain devices have been reverse engineered, and you can talk to them
unencrypted radio communication, and if they do use some sort as long as you have a transceiver for the frequency band around
of security, it’s quite weak and/or some proprietary algorithm that 433.92 MHz and the right software to decode and/or encode
doesn’t inspire much confidence. But there are so many available the protocol.
devices and they are so cheap, that you can’t ignore them. For
security reasons, I only use 433.92 MHz temperature sensors: I Some interesting devices are:
have one of them in almost every room of my house, and outside > temperature, humidity and weather sensors by Alecto, Cresta,
too. I wouldn’t trust 433.92 MHz devices for critical tasks. La Crosse, and Oregon Scientific;
> door/window sensors with Hall sensor;
In this chapter, I show you how you read measurements of these > switches and dimmers by Energenie, KlikAanKlikUit and
wireless temperature sensors and how to relay them to your MQTT LightwaveRF;
broker for further integration in your home automation system. > doorbell chimes by Byron and Chacon.
Note: in this book, I’m talking about 433.92 MHz, but depending You can also find many even cheaper devices on AliExpress and
on where you live you have to substitute this by another frequency. Banggood that support the same protocols. And there are even
For instance, in the Americas, the corresponding frequency is small PCBs such as the STX882 transmitter that you can connect to
915 MHz. Just make sure that you buy the correct devices for a microcontroller or an Arduino board to create your own wireless
your country. sensor boards.
Antenna
The next item you need is a good antenna. There are whole books
Figure 2: The RTL-SDR decodes a lot of wireless signals, including weather
sensors transmitting on 433.92 MHz. written about antenna theory, and I’m not going to delve into this
vast topic because I’m no antenna specialist.
One thing you should know for the choice of your antenna is
its length. This depends on the wavelength of the signal. The
wavelength equals the speed (in m/s) divided by the frequency
(in Hz), and is measured in metres (m). Let’s do the maths for
433.92 MHz communication. In air, the speed of the wave is virtu-
ally the speed of light. So the wavelength becomes:
299,792,458 m/s / 433,920,000 Hz = 0.69 m.
So the full wavelength is 69 cm, the half-wavelength is 34.5 cm,
and the quarter-wavelength is 17.25 cm. These are the theoretical
optimal lengths for an antenna to receive 433.92 MHz transmis-
sions. In practice, various factors are influencing the antenna’s
characteristics, including positioning, and there’s a rule of thumb
to subtract 5% from this theoretical length.
Again, this is not an antenna theory book, so I’m not going to talk
about the different types of antennas. Moreover, for reading sensor
values in your house it doesn’t even matter that much what the
quality of your antenna is. You could try experimenting with it, but
chances are that it just works if you buy a ‘433 MHz antenna’ for a
few euros on AliExpress or Banggood. If you don’t want to take any
chances, use an antenna included in a kit with the RTL-SDR. The
Figure 3: With the tripod mount, dipole base and telescopic antennas from official antenna kit (Figure 3) has telescopic dipole antennas you
the RTL-SDR kit, you have all you need to receive measurements from all can extend from 5 cm to 1 m, which covers the optimal wavelengths
your 433.92 MHz sensors. for the 433.92 MHz frequency [2].
To Dashboar
d
Project Nam Code View Code as .ino Component L
e e ist
W orkspac to Save
Simulate
Circuits Online
By Florian Schäffer (Germany) It is often the case that you don’t have all the
components required to build a circuit that is
developing in your mind. Or, perhaps the circuit
you wish to develop uses dangerously high voltages
and currents. In such cases, it makes sense to use
a simulator to test the idea in safety. Simulators
are now commonly available, with the Tinkercad
Circuits platform covered here accessible in your web
browser. As well as simulating circuits, it can also
execute Arduino code, as we show here.
8. When you have finished building the circuit you can test its
electrical functions and simulate it. Just click on Start Simulation at
the top of the screen. A brief animation will show the USB plug be-
ing plugged into the Arduino to show that it is now being provided
5. In many cases it is possible to adjust the parameters of a with power, and the ‘ON’ LED will light. At the moment, however,
component such as colour, type or dimensions by clicking on it there is no program for the Arduino to execute. The power supply
in the working area. This opens a small dialogue box showing the will also show its output voltage and the instantaneous current be-
settings that can be changed. Click on the power supply and set ing drawn.
the Voltage to ‘5’. You can also use a decimal point for this value if
required.
9. You can click with the mouse on the controls of the pow-
er supply and drag them around. The main part of the circuit will
withstand up to around 18 V, but not the Arduino connected over
the blue wire. In real life you would destroy the microcontroller like
this, but in this simulation you cannot do any damage. The piezo
sounder will emit a spluttering sound if you have a loudspeaker
connected to your PC. You can use the mouse to adjust the blue
potentiometer at the top left of the breadboard: as you turn it, the
sound will change.
void setup()
{
pinMode(iopin, INPUT);
Serial.begin(9600);
}
void loop()
{
Serial.println(digitalRead(iopin));
delay(10);
} 14. Turn the potentiometer and, as the sound changes, you will
also see the displayed waveform change.
12. When you next click on Start Simulation the program code
will also be executed. If there are any syntax errors in your program
they will be highlighted in the same way as in the Arduino IDE and
must, of course, be fixed before continuing.
The work bench of the late Bob Pease, inventor of the in-beard but could not find quickly enough or — even worse — deliberately
breadboard, is an infamous example of a messy workspace [1]. We not ordered components that were desperately required because I
know better of course but an unsuspecting layman will have trouble incorrectly thought I still had plenty of them. There was, therefore,
spotting the difference between our bench and a photo of a disaster plenty of scope for improvement…
area after a tropical cyclone has passed through. Although often
incorrectly attributed to Albert Einstein, we can still take solace Many of us have a tendency to sort their components nicely by type
in the quote: “If a cluttered desk is a sign of a cluttered mind, of and by value in storage containers or cabinets with drawers, with
what, then, is an empty desk a sign?” the surreptitious ulterior motive of collecting as complete a series
of values as possible, such as the entire E24-series of resistors. This
Chaos is not only a theory is a relatively good system for hobbyists, electronics designers and
Although I have much to learn from Bob Pease, I have to admit with repairers but, when you are involved with manufacturing, this is
blushing cheeks that I am an incorrigible slob. With my unstoppa- far from flexible.
ble tendency for ‘heap forming’ I have driven my parents, many a
former employer and even my partner to desperation. I buy the basic components and their through-hole equivalents in
large quantities, depending on what I need for my products. As such
Years ago I was particularly busy with SMD components and we it is not so wise to have thousands of every value of resistor in the
all know that it is better to leave them in their little bags, unless E24-series in stock (as an example) when more than three-quar-
you want them to get lost or all mixed up. From this good habit ters of those values are practically never used. And that doesn’t
the little bags with components piled up and, after a while, I had even take into consideration sorting them all nicely into drawers.
multiple stacks of storage boxes filled with various components.
Thanks to a little industrial espionage during an open-day at one
The consequences are predictable: every time I wanted to build of our suppliers I have come up with a better system. I now use
a small series of circuit boards I spent more time looking for all racks and boxes where every box has its own code that indicates its
the parts than the time it took to populate and reflow the boards location, such as “A5K0”. This means rack “A”, shelf “5”, position “K”
themselves. How often have I ordered parts again that I still had and then the first box from front to back. To know where a compo-
nent is I use a spreadsheet. The advantage of selection of bright LEDs at the well-known wholesalers is rather
this system is that components do not need to poor and that is why I occasionally place an order via eBay.
be sorted. The box with microcontrollers can be
located next to a box with screws. You can also Normally I keep the websites of four or so suppliers open in different
easily move components around and empty tabs in my browser. Whoever offers a component in the quantity
locations can be reused for something else. I desire, at the best price, has my business. Because it is not likely
that one supplier has everything in stock that I need, I usually end
The spreadsheet is not really the optimal up with orders from at least three different suppliers. Consequently
approach but, unfortunately, I have not a parade of delivery vans turns up a few days later at my door. And
yet found an affordable and more suitable then you get the jealous looks from the neighbour across the road
software solution. Additionally, there is who thinks that nearly every day is Christmas over here. Quite
always something that is not quite right. Now what he would do with a few thousand MOSFETs is anyone’s guess.
I actually spend more time on the booking-in
and booking-out of components and retriev- It also worthwhile to take a good look at the price break for bulk
ing them from these boxes than populating purchases. These normally encourage you to buy much more than
and reflowing my circuit boards. Naturally I sometimes forget to you were intending. This has resulted in some strange pricing
book something in or out with the result that some orders still go outcomes on more than one occasion. I have encountered that
wrong. Perhaps the chaos was not so bad after all. However, it is one hundred pieces of an IC came to the exact same price as 50
now much quicker to pass on the stock levels at the end of the year pieces. I’ve come to the conclusion that free components really
to our ‘bean counter’ — at least that is an improvement. do exist!
200556-04
Part ordering for dummies
For improved ‘heap forming’ you obviously require components
and then preferably different ones in large quantities. To be honest,
I haven’t been to a classic electronics shop in years and these days I
order everything online from the well-known wholesalers. Price is
obviously important. However, I nevertheless recommend that, for Questions or Comments?
critical components and semiconductors, you refrain from using Do you have questions or comments regarding this article?
suppliers in the Far East. Also, for reasons unknown to me, the Then email Elektor at editor@elektor.com.
WEB LINK
[1] Bob Pease, ‘Whats All This Messy Office Stuff Anyhow?’: https://bit.ly/39AxMHx
Starting Out
in Electronics (6)
Easier Than Imagined!
By Eric Bogers (Elektor Netherlands) Putting this aside, let’s first take a good look at indicate the value of the resistor. This has to
what resistors actually look like. In Figure 1 we be multiplied by a (power of 10) factor that
As promised in the previous have portrayed the most common examples. is indicated by the penultimate band. The
At the bottom you will see a metal-film resistor last band indicates the tolerance. Tolerance
episode of this series, we and a carbon-film resistor above that, both — what’s that? When we take a batch of
will now occupy ourselves with a power rating of 0.25 W. The power 1000 Ω resistors and measure them with a
with ‘tangible’ components rating indicates the maximum power that very accurate ohmmeter, we will find that no
a resistor can convert into heat without the two resistors have the exact same value. For
— with resistors, to be more resistor failing. This is something to keep an example, one will be 1001.3 Ω, and another
specific. A great deal more eye on! 998.6 Ω, an so on. This is because of unavoid-
can be said about them able small variations during manufacturing.
In addition to the maximum power rating we The tolerance indicates the limits of the range
than that which you may also need to consider maximum voltage rating. of values that the resistor can have, with the
initially appreciate: there If this is exceeded, the resistor can break-over actual value lying somewhere in between.
are resistors, resistors, and and it will likely fail. With the common-or-gar- For a 1000-Ω resistor with a tolerance of 5%
den resistors that are typically used in hobby (this is a ‘normal’ carbon-film resistor) the
resistors… projects, the maximum voltage is generally actual value is somewhere between 950 Ω
rated at 250 V, so we don’t have to worry too and 1050 Ω; with a 1% version (a metal-film
much about this in practice. resistor) the actual value is between 990 Ω
Resistors and 1010 Ω. There is also a chance that outliers
Resistors are classified as passive compo- Back to Figure 1: in the middle on the left exist with values outside the tolerance range,
nents because (in contrast to active compo- are two resistors with a higher power rating but this does not happen very often.
nents) they cannot amplify signals. Passive (0.5 W and 1 W) and, right at the top, a cement
components include resistors, capacitors version with a resistance of 39 Ω that can By the way, for most applications the 5%
and inductors; active components include handle 11 W. The power resistor in the middle carbon-film resistors are good enough. Only
transistors, triacs and, yes, diodes are also on the right is a type that can be bolted to a when it is really necessary to be very accurate
considered to be active components. This isn’t heatsink that can handle up to 25 W. (such as filter circuits) and/or when the circuit
correct, strictly speaking (a diode, after all, must be as low-noise as possible (a high-end
does not amplify), but because we tradition- Normal resistors for regular use are small (the audio amplifier) do we use the, more expen-
ally pile all the semiconductors into one great bottom two in Figure 1) — so small in fact that sive, metal-film resistors.
heap, diodes are also called ‘active’. it is impossible to print their resistance value
on them in a legible form. This is why the value Table 1 lists the colour codes for resistors. A
is indicated with coloured bands. These days 1% metal-film resistor with a value of 1 kΩ has,
there are much smaller components available, according to Table 1, the colour code brown,
known as SMDs or Surface Mount Devices black, black, brown, brown. Unfortunately,
but, because this series of articles is aimed in this case it is not immediately obvious in
at the electronics beginner and SMDs are which direction the colour code should be
not really suitable for an initial introduction, read — in reverse it could be a resistor of
we will not go into these. We will stick with 110 Ω. However, don’t give up too soon —
trusty ‘leaded’, easily-handled components. practice makes perfect and in the event of
doubt an ohmmeter can be the final arbiter!
The colour code
There are resistors with both four and five Another disadvantage of the coloured
Figure 1. A few resistors. coloured bands. The first two or three bands bands is that the colours red and orange
are sometimes difficult to distinguish. In is, of course, the volume control of an ampli-
Table 2: Standard resistor values
case there is any doubt, again, reach for fier (although in the present digital era these
the ohmmeter. are now often digital encoders). The there E3 E6 E12 E24
are the trimpots that are generally inside the 1 1 1 1
Resistors are (for obvious reasons) not device (usually on the circuit board) and are
produced in every conceivable value. Instead intended for once-only adjustment using a 1.1
they are manufactured in standardised small screwdriver or special trimming tool. 1.2 1.2
E-series. Here the ratio of two consecutive
values within a decade is more or less the Figure 2 shows various examples of (trim) 1.3
same. The E-values are in turn produced pots. On the right you see the slide potenti- 1.5 1.5 1.5
in different series of decades (for example ometer, or fader, that is often used in mixing
1.6
2.2 Ω, 22 Ω, 220 Ω, 2.2 kΩ, 22 kΩ, 220 kΩ and panels. In the middle are two ordinary poten-
2.2 MΩ). Table 2 shows the most common E tiometers with a mono version at the top and 1.8 1.8
series values for E3, E6, E12 and E24, where a stereo version at the bottom. Such a stereo
2.0
the number indicates the number of values potentiometer is really two mono potentiom-
per decade. For precision applications there eters on a common shaft. 2.2 2.2 2.2 2.2
are the E48, E96 and E192 series, i.e. a total 2.4
of seven standardised E series. In the rotary potentiometer a sliding contact
moves back and forth along a carbon track. 2.7 2.7
By the way, there is also an R-series, but the Such potentiometers often start to ‘crackle’ 3.0
probability that you will get involved with after some time due to age and contamination.
3.3 3.3 3.3
them in electronics is very low. In electrical This is extremely undesirable, particularly with
engineering you will come across R-series only audio amplifiers. If a particular potentiome- 3.6
in relation to fuses or miniature circuit breakers. ter is not hermetically sealed then a special
3.9 3.9
If you need an extremely precise and, at the spray cleaner can give temporary relief (with
same time, awkward value that does not occur the emphasis on temporary). Otherwise you 4.3
in any of the E series, then it can be achieved can try turning it vigorously from one end to
4.7 4.7 4.7 4.7
with an appropriately selected parallel and/ the other a few times, but this too will likely
or series connection of E24 resistors. Or you only be a temporary solution. 5.1
could use a variable resistor… 5.6 5.6
Cermet potentiometers are less sensitive to
Variable resistors these ageing symptoms (and are therefore 6.2
Potentiometers, also known simply as a ‘pot’, also more expensive). Figure 2 at the top in 6.8 6.8 6.8
and trimpots are resistors whose resistance the middle provides two examples (mono on
7.5
value can be changed. Potentiometers have the right and stereo on the left). Finally, at the
a shaft that protrudes through a hole in the top left of Figure 2, there are two closed-vari- 8.2 8.2
enclosure of a device that can be operated ant trimpots that are a little less sensitive to
9.1
by the user. The most well-known example dirt and dust ingress.
Contributors
Idea and illustrations: Michel Ebner
Figure 3. Potentiometers: schematic symbols. Figure 4. Voltage dependent resistor (VDR). Text: Eric Bogers
Translation: Arthur de Beun
Editing: Stuart Cording
Layout: Giel Dols
quantity. The most common ones are briefly current increases further until it finally reaches
discussed below. its nominal value. These current-limiting resis-
tors are usually bypassed by an (electrome-
Figure 4 shows the schematic symbol for a chanical) relay after a few seconds so that no
Voltage Dependent Resistor (VDR). Once a more power is lost in the NTC-resistor.
certain voltage has been exceeded, the resis-
tance of a VDR becomes very low. In this Finally, Figure 6 shows a Light Dependent
way the component can protect other parts Resistor (LDR). The resistance value of the
from over-voltage conditions. VDRs are often LDR decreases when the light that falls on it
Figure 6. Light dependent resistor (LDR).
used to protect power transformers against becomes brighter. In the past, these resistors
over-voltage (something that could happen were often used in optical sensors. However,
when the neutral is not connected correctly). one of their disadvantages is that they are
There will then be enough current through the relatively slow to react to changes in light
Linear or logarithmic? VDR to blow the mains fuse and thus avoid level. These days photo-diodes or photo-tran-
Potentiometers in parts lists often have the further damage. However, the VDR often has sistors are preferred for such applications.
abbreviation log or lin in the specification. This to be replaced after such failures too. This brings us to the end of our discussion
means logarithmic and linear respectively on the topic of resistors. Next time we will
and this indicates how the resistance value In Figure 5 we see several symbols for continue with capacitors.
varies as a function of the angle of rotation. temperature-sensitive resistors. The two 200551-04
Logarithmic potentiometers are mainly used symbols on the left represent an NTC resistor
as volume controls in amplifiers because (Negative Temperature Coefficient); the two The magazine article series “Starting Out in Electronics”
our hearing has a more or less logarithmic symbols on the right represent a PTC resis- is based on the book Basic Electronics for Beginners by
characteristic. tor (Positive Temperature Coefficient). The Michael Ebner, published by Elektor.
resistance value of an NTC resistor decreases
In Figure 3 you can see the schematic symbols as it becomes warmer; with a PTC resistor
for potentiometers: a potentiometer on the this is, of course, the exact opposite. NTC
left, in the middle a trimpot, and the equiva- resistors are sometimes used to limit inrush
lent circuit on the right. The value of each of currents. In conventional power amplifiers
the resistors depends on the position of the there are usually heavy mains transformers
wiper (the middle connection of the schematic with large, discharged smoothing capaci-
symbol). As with ordinary resistors, potenti- tors when powered off. As a result there is RELATED PRODUCTS
ometers also have a maximum power rating. an extremely large incoming current at turn-on
that could blow the mains fuse. An NTC can Basic Electronics for Beginners
Special resistors help prevent this problem by limiting the initial > Book: www.elektor.com/13950
There are a whole range of resistors whose inrush current. As the NTC becomes warmer, > E-book: www.elektor.com/18232
value is dependent on a specific physical as a result of the current flowing through it, the
Homebrew CPUs
The discrete microcontroller
By Dennis Kuschel (Germany)
Modern microcontrollers
make it possible to cram a
whole lot of functionality into
an extremely small volume.
Things that, in the past,
required a bag full of chips
to accomplish can now be
realised in a single IC without
any great difficulty. Of course,
such a microcontroller still
needs to be programmed and Figure 1: Dennis Kuschel in his home laboratory. The furnishings can be described as almost spartan.
this is often done with the aid
of high-level programming
languages. But this has the disadvantage that the designer can lose the link to what goes on
at the port or transistor level inside such devices.
This was also Dennis Kuschel’s train of thought when he began his building their own because the cost of the complete MyCPU plus
work on building a discrete microcontroller with individual logic peripherals quickly approaches €1,000. That is why I decided (after
ICs. Perhaps we should call it a ‘macrocontroller’ really. Here we 20 years) to begin a new project: a simple and as-cheap-as-possi-
hand over to Dennis: ble computer that is, of course, entirely built from discrete parts.
It had to meet two conditions. Firstly, it had to do without an ALU
“Figure 1 shows my work space at home. I only own a few items (Arithmetic Logic Unit) for the simple reason that the previously
of measurment equipment — an oscilloscope and two digital ubiquitous ALU chip 74LC181 is no longer available and alterna-
multimeters. I don’t need anything else and I’m really not missing
anything either. On my work bench you can see an example of the
MyNOR computer where I have replaced 10 of the ICs with discrete
transistor circuits (the cheerfully-coloured jumper wires).
“For Christmas in 1989 I received my first computer: a Commodore
64. I quickly wanted to do more than simply play games — I
preferred to write my own programs and learn how such a device
actually works. Four years later (I was then 17) I built a new computer
from the salvaged parts of a C64 that I then programmed in assem-
bler. During my electrotechnology studies in the 90s, the idea of
building a CPU from simple logic gates and ICs came to me. A few
years later MyCPU [1] was born. This is a computer built from many
tens of logic ICs from the 7400-series CMOS logic family that runs
a version of C64 Basic.
“The MyCPU received a lot of attention at computer festivals and Figure 2: This is the heart of the MyNOR computer: a single, discretely-built
hobby fairs, but many of those who were interested shied away from NOR gate.
tives have become too complicated. And, secondly, it would have erable number of peripherals: a 64 kB EEPROM for ‘mass storage’,
to suffice with a single programmable memory IC (EEPROM). while 8 digital inputs and 24 digital outputs provide communication
with the outside world. These 32 I/Os allow the usual interfaces
“My new computer uses only a single NOR-gate for its arithmetic (RS232, I2C and SPI) to be realised in software.
– an extremely simple logic unit that I chose because it is easily
built using two MOSFET transistors and a resistor (Figure 2). All “This single-board computer can achieve a surprising number of
arithmetical operations (such as AND, OR, EXOR, add and subtract) things. For example, I built a simple calculator in the operating
are obtained in software from combining many individual NOR system that can be operated via the RS-232 interface. This calcu-
operations. lator primarily serves as proof that floating-point operations can
be carried out by a single NOR-gate! Furthermore, the operating
“Because of the central NOR gate I have christened my new system contains a simple monitor program that allows assem-
computer MyNOR [2]. The total number of parts is so few that the bly-language instructions to be entered. This way you can write
entire circuit fits on a circuit board measuring 10 × 13 cm. Figure 3 your own assembly-language programs directly on MyNOR and
shows the formal portrait of MyNOR, while the photo on the right store them in the EEPROM (this is a bit in the style of the C64).
shows what is where on the circuit board. It also contains a consid- But it is, of course, also possible to upload a complete program.
This is done using a text file that represents the binary program
in a special format. A little bit of patience is required because the
connection at 2400 baud is not blindingly fast.
“It becomes really exciting when this single-board computer is
used without the umbilical cord to a PC. For this purpose I have
developed two expansion boards. The first contains 20 pushbut-
tons, an LED and eight 7-segment displays along with the requisite
transistors for driving them. The displays and pushbuttons are
multiplexed in the usual way. I use the ‘pocket calculator’ built in
this manner every day at work.
“The second expansion board turns MyNOR into a real small
computer. This board contains, in addition to the usual pushbut-
tons, a 4 × 20 LCD, a little loudspeaker, a battery-backed real-time
clock and a temperature sensor. When MyNOR is expanded with
Figure 4: The pocket calculator on the left and, on the right, the MyNOR this board there are an endless number of possibilities: I have
with keyboard and display. already programmed a few games (minesweeper, Tetris), a kitchen
timer, a music box and an I2C-bus scanner. Both expansion boards only 22 ICs, it is a nice challenge to replace the 19 logic ICs with
can be seen in Figure 4. discreet transistor circuits. The first experiments toward this goal
are showing much promise. Figure 6 shows two ICs built using
“The first version of MyNOR on a ‘real’ circuit board was not quite individual transistors.
perfect. Nevertheless, this version (including the 7-segment expan-
sion) is still serving a purpose: I converted MyNOR v1.0 into a “By the way, I’m not the only one who is busy with DIY CPUs. Many
teeth-brushing timer for my children (Figure 5). of us have come together in the ‘Homebrew CPU Webring’; a visit
to their website [3] is certainly worthwhile.”
“At the moment I’m busy with the further ‘discretising’ of the 200552-04
computer. Because the entire MyNOR computer comprises of
WEB LINKS
Contributors
[1] MyCPU: www.mycpu.eu
Text and photos: Editing: Stuart Cording
Dennis Kuschel Layout: Giel Dols [2] MyNOR: www.mynor.org
Translation: Arthur de Beun [3] Homebrew CPU Ring: www.homebrewcpuring.org
Home automation done properly is like an invisible hand that gently pushes you up a
hill. When it’s there, it makes life a bit more comfortable; when it isn’t, you can still climb
that hill. This article is about designing a thermostat for such a home automation system.
Automated or not, its traditional user interface always keeps you in control of the room’s
temperature.
About one year ago, I decided to have a go at home automation. In this setup, Home Assistant — running on a Raspberry Pi — plays
My first milestone was the automation of the thermostat in our the role of thermostat, meaning that it decides when to turn on or
living room. I did this by replacing the existing wall thermostat by off the heater. The desktop thermostat itself has become a simple
the Wi-Fi Desktop Thermostat (Elektor project 160269, published remote-controlled relay with some LEDs.
in Elektor, January/February 2018 [1][2]) that I had reprogrammed
with ESPHome-based firmware. The new firmware exposed all the Nice, But…
controls of the desktop thermostat (i.e., one relay, two pushbuttons The system worked fine and helped us comfortably through the winter
and three LEDs), allowing them to be automated by a home automa- of 2019-2020. However, it had a few inconveniences:
tion controller like Home Assistant.
Past Proof
The second point is related to the first as Home Assistant and Raspberry
Pi may disappear someday too. But there is more. I kind of know how
to deal with Home Assistant running on a Raspberry Pi, but most
people I know do not. To allow other people to use my automated
thermostat, it must be “past-proof” as well. It should look like a classic
wall thermostat and behave like one. The automation part may not be
imposed but should be discreetly optional instead. It is there for those
who want to use it, but for those who don’t, it may not be in the way.
A Matter of Taste
The third issue is somewhat personal. The automated desktop thermo-
stat ended up dangling at the end of a length of wire connected to a
hole in the wall where the old thermostat used to be (Figure 1). A few
unused mains-connected wires sticking out of the wall were protected
with bits of isolation tape against silly humans. Also, as the desktop
thermostat needs a 5 V power supply on a USB connector, it was
powered by a phone charger plugged into a nearby power strip. This
meant that there were several very visible wires going to the device
where the original thermostat had none. Although an excellent conver-
sation starter, most visitors didn’t think the system looked very nice
(but “ugly”, “weird” and “dangerous” instead).
K1 N
1
IRM-02-5
1 Re1
N RY211006 D1
2
L
3
1N4148
4
NC D
5 T1
COM
6 R6
NO G
1k
+3V3 2N7002
S
R11 R3 R4 R8 R7 R5 3 DS18B20
C2 C5
120k
10k
10k
10k
10k
10k
C1
100n 100 2
6V3
IC2 100n
K2
1 22 1
REST TX TXD
2 MOD1 21 2
ADC ESP-12E RX RXD
3 20 3
P1 CH_PD GPIO5 RST
4 19 4
47k GPIO16 GPIO4 GND
5 18 5
GPIO14 GPIO0 P0
6 17
GPIO12 GPIO2
7 16
GPIO13 GPIO15
R2 8 15 R9 R1
S2 S1 VCC GND
GPIO10
GPIO9
SCLK
MISO
MOSI
220
220
220
R10
CS0
10k
I added a potentiometer with a voltage limiting resistor because the Wi-Fi rest, I now had to do automations inside ESPHome. This programming
module cannot handle voltages higher than 1.1 V. I kept the two pushbut- and configuring is done in the YAML file of the thermostat’s ESPHome
tons and the three LEDs as they might come in handy at some point. project (see “Home Automation Made Easy” [3]).
It was a lucky coincidence that the AC/DC module was just small Measure Room Temperature
enough to fit under the plastic knob support of the potentiometer. The First, declare the temperature sensor that measures the room tempera-
potentiometer, power switch and mains terminal block were recovered ture. As the sensor used is a DS18B20 (originally from Dallas, now Maxim
from the old thermostat (Figure 3). I had to replace the relay by a 5 V or even Analog Devices) connected to GPIO pin 5, and since ESPHome
type as the old thermostat’s relay was a 48-V type. I did not manage has a special Dallas component, this translates to the following entries:
to fit the desktop thermostat’s relay, but, lucky me once more, the old
thermostat’s relay was a type from an industry-standard family that dallas:
is still available and that exists in 5 V. - pin: GPIO5
Putting it all on a PCB that fitted in the original enclosure required a sensor:
lot of measuring, but I succeeded in the end. All the SMT components - platform: dallas
including the Wi-Fi module went on the bottom side of the board address: 0x6D00000C24013928
(Figure 4), while all the through-hole parts found a place on the top name: “Measured temperature”
id: t_room
side. A little bit extra board surface was gained by obstructing a couple
filters:
of unused mounting holes of the enclosure. The fitting also implied
- offset: 0.0
cutting away some plastic obstacles inside the enclosure. To route all
the tracks, a flexible approach of recommended isolation standards
was unfortunately unavoidable. The first line tells ESPHome to include its Dallas 1-wire communica-
tion module and connect GPIO5 to it. The sensor then is of the dallas
Software platform. The address is optional. However, if you specify it, it must
The ESPHome firmware that I had compiled for my first setup also be correct; you can get it from the ESPHome log (don’t use mine, it is
required rethinking. Instead of simply exposing all the sensors and unique). Specifying an id (t_room, pun not intended) is required here
actuators of the thermostat and letting Home Assistant take care of the because we will need to refer to the sensor from somewhere else inside
Figure 4: Everything SMT is mounted on the backside of the board. The Figure 6: Assembly completed. The two pushbuttons are accessible through
traces connected to the heater (right upper corner) were reinforced with two cut-outs (left) and the sensor sticks out of what is the bottom. The
extra solder to allow them to carry large currents without overheating. green and yellow LEDs are only visible through the ventilation slits to avoid
The slot right below them provides galvanic isolation between the high- lighting the room at night. Using different colours for them makes it easy to
and low-voltage parts. The black thingy sticking out on the right is the see which one is turned on.
temperature sensor, protected by heat-shrink tubing. All the heat-producing
parts are located on the left side of the board and are supposed to point
upwards after installation of the thermostat.
Filters are executed in the order they appear in, meaning that the
delta filter operates on the value converted to degrees Celsius, and
not directly on the input voltage. Its value should be small, otherwise RELATED PRODUCTS
it is difficult to nudge the thermostat up or down just a little bit, which
makes all the difference in user comfort.
> ESP-12F, ESP8266-based Wi-Fi module
www.elektor.com/esp-12f-esp8266-based-wi-fi-module-160100-92
Finalising the Device
With the YAML configuration file ready, the firmware can be uploaded > Wi-Fi Desktop Thermostat - bare PCB (160269-1)
to the Wi-Fi module. The first time (i.e., with a module that is not yet www.elektor.com/wi-fi-desktop-thermostat-bare-pcb-160269-1
running ESPHome-compatible software) the serial port must be used
for this (available on header K2). Refer to [3] for the exact proce-
> NodeMCU ESP8266 microcontroller board
www.elektor.com/nodemcu-microcontroller-board-with-esp8266-and-lua
dure. Once the device is executing ESPHome with Over-the-Air (OTA)
programming enabled (when the YAML file contains the line ota:), the > H. Henrik Skovgaard, IoT Home Hacks with
thermostat can be reprogrammed without being physically connected ESP8266 (Elektor, 2020)
to the development system. In other words, it can be installed in place www.elektor.com/iot-home-hacks-with-esp8266
of the existing thermostat.
The thermostat is mounted so that its temperature sensor is not heated
WEB LINKS
[1] R. Aarts & C. Valens, “Wi-Fi Desktop Thermostat,” Elektor, Jan/Feb 2018: www.elektormagazine.com/160269
[2] C. Valens, “Wi-Fi Thermostat at Elektor Labs,” Elektor Labs, 2018: http://bit.ly/wifi-thermostat
[3] C. Valens, “Home Automation Made Easy,” Elektor, Sep/Oct 2020: www.elektormagazine.com/200019-01
Developer’s Zone
Tips & Tricks, Best Practices
and Other Useful Information
High-side or Low-side Switching? than short circuits to the positive power line. Think for instance
In systems employing high-side switching, the switch is inserted of cars or machines where most of the structure is connected to
between the positive power line and the load. Low-side switching ground. In such cases it is safer to disconnect the load from the
by contrast connects the load to ground (Figure 1). The principles battery than from ground. Also, in humid environments, this
of operation of high-side and low-side switching are easy enough usually results in less connector corrosion as the load carries no
to grasp, but when do you prefer one method over the other? It’s voltage in the off state.
all application dependent for sure.
Power Switching Is Better With N-Type Devices
Because N-type transistors in general can carry more current than
P-types, they are preferable for switching heavy loads. Low-side
switching with N-type devices is easier than high-side switching
and can often be done by microcontroller ports without the need
Figure 1: Switch a load to for special drivers.
the supply rail (left) or to
ground (right)?
Using an N-type transistor for high-side switching is possible but
requires a control voltage higher than the (load) voltage connected
to its source or emitter. To pull the gate or base of the transistor above
its source or emitter voltage, some sort of charge pump is needed or
an extra supply. This complicates the design, not only making it more
expensive but also increasing its sensitivity to noise and interference.
Avoid Dangerous Situations Driving such a high-side switch with a PWM signal to control e.g.,
High-side switching (Figure 2) is the preferred switching technique the speed of a motor or the brightness of an LED can be problem-
in situations where short circuits to ground are likelier to occur atic because of the charge pump.
Figure 3: Low-side
switching is cheap and
easy. However, when a fuse
Figure 2: High-side must be added because the
switching is preferred when distance between the load
the risk of a short circuit and the controller is too big
to ground is higher than a (right), this configuration
short circuit to the supply. can become more
expensive than high-side
switching.
Conclusion?
The current sense method to choose depends on the application
Low-Side Current Sensing Is Cheap (again). High-side current sensing can detect if the load is
In the case of low-side current sensing, the typically small shorted or open, and the load remains referenced to ground.
voltage over the sense resistor is referenced to ground and can However, due to the common mode requirements, it is more
be amplified with low-cost, low-voltage op-amps before being complex and more costly than low-side sensing. Opting for a
digitised and processed further by for instance a microcontroller. dedicated current sensing IC may be the best way forward.
However, like the switch in low-side load switching, the sense
resistor introduces a small voltage drop that lifts the load from
system ground, possibly resulting in noise and ground bounce.
Bandwidth
First, the bandwidth of the two circuits is not
the same. The difference amplifier usually has a
(much) lower bandwidth than the current sense
amplifier and is therefore more suitable for
measuring the average current flowing through
a load. The current sense amplifier, on the other
Several methods exist for doing high-side current sensing. The current sense amplifier
hand, is fast and can measure instantaneous load and the current shunt monitor or difference amplifier shown here are two of them.
current at high frequencies.
CMR
Another important factor to consider is common-mode
rejection, or CMR. As the common mode voltage at the inputs is Power Consumption
high, even a small asymmetry between the two inputs will result Finally, there is power consumption, especially important in
in an error at the amplifier’s output. The difference amplifier (ultra) low-power applications. If connected directly to the
therefore needs high-precision resistors to keep the CMR error supply, the difference amplifier with its resistors will always
as low as possible. In the current sense amplifier, it is mainly consume some current even when the opamp is unpowered.
the opamp that determines CMR, a parameter controlled by its The current sense amplifier features a much higher input
manufacturer. impedance, which helps making batteries last longer.
No appetite for tackling a big project? That’s fortunate because here we have a few more
small circuits that are easy to build and perfect for keeping those ‘January blues’ at bay…
idea: Peter Neufeld (Germany) Some experimentation may be required here, and an impedance of 8-32 Ω. (It turned out
supported by information from the datasheet that the volume was too high when using a
Tranquili-T and the Internet, with other MP3 players. 4 Ω speaker.) Figure 2 shows the ’guts’ of a
The big ideas and projects resulting from the version built around the DFPlayer Mini while
efforts of an electronics enthusiast are, unfor- With respect to the choice of loudspeaker, Figure 3 shows a completed Tranquili-T in
tunately, not noticed by friends and family — select a model that is as small and flat as all its glory.
that DIY oscillator or servo controller can’t possible with a load capacity of at least 0.5 W
really be called a crowd pleaser. However,
the soothing Tranquili-T by Mr. Neufeld has
received much praise, resulting in him build-
ing several devices to give to friends and
R3 LS1
acquaintances. 500mW
4...32
S1
150...220
6k2
4V5...5V
500mAh
The soothing effect is then amplified with a
D1 S2 S3 S4 S5
rainbow LED that provides subdued lighting
in a dark room. A video from the author shows V–, < V+, > V–, < V+, >
the Tranquili-T in action [1]. 200557-001
We can be brief about the power supply:
Figure 1: The heart of the circuit is realized with an MP3 player (module).
anything that supplies 4.5 to 5.0 V can be
used. For example, three 1.5 V batteries
are an option, but remember that the LED
draws around 20 mA and the player draws
a further 50 mA at an average sound level.
A USB power bank is a good option, as then
you don’t have to worry about dead batteries.
MP3 players with integrated Class-D ampli-
fiers are preferred for simplicity. The author
has had good experience with the JQ6500
and the DFplayer Mini. These are available at
reasonable prices from the usual suppliers in
the Far East. Figure 1 shows two approaches
for implementing the volume control outlined
in seperate boxes. The variant using S2 and S3
uses two digital inputs; the variant using S4
and S5 uses a single analogue input in combi-
nation with two different resistors. The values Figure 2: The electronics can be built compactly Figure 3: The final Tranquili-T in all its glory.
drawn in the diagram apply to the JQ6500. on a small piece of prototyping board.
idea: Andrey M. Shustov (Russia) discharged. Transistor T1 turns off again due idea: Elektor Labs
and Michael A. Shustov (Germany) to the discharge of capacitor C1 and thus
switches on transistor T2. The process is then Wandering mono audio
Three shades of Schmitt trigger repeated endlessly. Before digital signal processing entered
oscillator the scene, musicians had to use ingenious
Schmitt triggers or asymmetrical emitter-cou- The oscillation frequency of the pulse oscil- electromechanical contraptions to create
pled triggers can be used to construct simple lator in Figure 4 can be changed propor- certain sound effects. Take the Hammond
wide-range pulse oscillators. Transforming a tionally by adjusting the capacitance of organ, the electromechanical precursor of the
Schmitt trigger device into a oscillator is quite capacitor C1. Potentiometer R5 permits synthesiser (somewhat succinctly expressed),
simple. The output of the trigger is connected a frequency range greater than 1:10 to be an instrument that musicians like Walter
back to the input by a resistor and a capacitor covered. LED1 provides a visual feedback Wanderley used to create delightful sounds.
is connected between the input of the trigger of the frequency tuning. The LED is at its There was, however, one drawback: such an
and the common supply rail. brightest at the beginning of the range and organ was mono. This resulted in a rather
is least bright at the end of the range. The feeble sound eminating when on stage in front
Figures 4, 5 and 6 show practical circuits oscillator operates over a frequency range of an audience.
of pulse oscillators, based on the modified of 3 to 30 Hz. Using the values shown in
Schmitt trigger. A bridge circuit consisting of a the circuit, the current through LED1 varies Fortunately there was Donald Leslie who
resistive divider, where the emitter of the input between 20 and 2 mA at a supply voltage of developed a particularly clever solution to
transistor is connected to the mid-point of a 9 V. When the supply voltage is varied from this problem. He came up with the idea that
resistive divider, and a time-setting RC circuit, 5 to 15 V, the oscillation frequency changes a rotating loudspeaker could ’swing’ the mono
formed by the additional hookup elements, by no more than 10%. sound around the room, creating a much
all act to convert a trigger into a repetitive wider sound image. Due to the moving parts,
pulse oscillator. The pulse oscillators in Figure 5 and a rotating loudspeaker is difficult to achieve
Figure 6 also operate at a nominal supply electrically. The Leslie loudspeaker solved this
The p-n transition of the transistor lies voltage of 9 V across the frequency range by mounting a rotating cylinder with a sound
between the diagonally opposite pair of 0.8 to 10 kHz and 0.35 to 2.8 kHz respectively. hole horizontally above the loudspeaker —
connections of the bridge. When capac- The oscillator in Figure 5 is controlled by more or less as sketched in Figure 7.
itor C1 is discharged, transistor T1 blocks changing the ratio of the resistive voltage
and transistor T2 conducts. The voltage divider arms (resistors R4, R5 and R6, the Here we treat you to a (very, very simple)
across then capacitor rises again. Once it right half the bridge circuit). The opera- electronic equivalent that may not match
exceeds the voltage of the mid-point of the tion mode of the oscillator in Figure 6 is the quality of an original (and very expen-
resistor-divider’s mid-point by several volts, controlled by resistor chain R2, R3 and R4 sive) Leslie speaker, but it remains interesting
input transistor T1 conducts again, turning that regulate the discharge/charge processes enough for your own experiments. Figure 8
T2 off. This de-energises the resistor-di- in the left half of the bridge circuit. shows the schematic.
vider and the time-setting capacitor C1 is
Figure 8: The circuit (left) is relatively simple. The wiring for the potentiometer is shown in the centre. The connection to a stereo amplifier is shown on the
right.
The Raspberry Pi will act as the base node of the RF24 network and download the Gerber files for the HAT from the project’s part list
is responsible for processing the sensor values it receives from the page [1]. You can also order this PCB directly from PCBWay [2].
Arduino node (or nodes, if you have more than one). [The Arduino
node is described in preceding chapters in the book not excerpted If you prefer to prototype this circuit using the breadboard, please
here, Ed.]. In this chapter, I will show you how to connect the RF24 consult the connections table in Figure 2, and the schematic
module to the Raspberry Pi. You can choose to do the wiring on diagram of the HAT PCB in Figure 3. You can get a high-resolution
a breadboard, or to use a special HAT I designed for this purpose. version of the HAT schematic from the same project parts list [3].
I implemented my Raspberry Pi RF24 module using the HAT break-
out. You can see it in action in Figure 1. The HAT accommodates In the following list I include all the parts that you will need to
the nRF24 transceiver module, the DHT22, a momentary button, implement that schematic diagram of Figure 2. With some of
and two LEDs (power indicator, and activity indicator). You can these parts, such as the button and DHT22 sensor, you have already
Figure 1: The Raspberry Pi HAT installed on a Raspberry Pi Zero W. Figure 2: The connection details for the nRF24 and DHT22 modules.
connected in earlier parts of this project. If you are working your this function by studying the driver’s source code [5].
way through the project, the only new components are the nRF24 > Once the radio object is created and initialized, the script
transceiver and its bypass capacitor. creates the network object using the RF24Network construc-
tor. This is the object that makes it possible for the Raspberry
Parts needed: Pi to receive a transmission from the Arduino node. The only
> one DHT22; parameter needed to create the network object is the radio
> one nRF24 breakout; object we created on the previous line. You can learn more
> two resistors, 10 kΩ; about the RF24Network constructor in the source code of
> two resistors, 330 Ω; RF24Network.h [6], on line 373.
> one LED, red (power indicator); > On the next line, with octlit = lambda n: int(n, 8) we
> one LED, blue (activity indicator); create a lambda function which we use later to convert a
> one electrolytic capacitor, 220 μF or similar. decimal number into an octal number. We do this because
the RF24 Network driver uses the octal system for the node
The Raspberry Pi nRF24 receiver script addresses. In Python, a lambda function [7] is similar to a
In this chapter, I will explain the functionality of the Python receiver regular function (where you use the def keyword) but has
script that runs on the Raspberry Pi and takes care of the nRF24 no name. They are convenient to use when you want to do
communications. Note this script will not work ‘out of the box’. things like evaluate a single expression, as is the case here: we
It depends on the RF24 and RF24Network C-language drivers and pass a decimal number to octlit, and the lambda function
the Python wrappers that I will show you how to set up in the next will return its octal-base equivalent using the Python int()
chapter. For now, let’s concentrate on the Python receiver script. You function [8].
can download and then view the full source code of this script in the > In this_node = octlit("00"), we use the octlit lambda to
project repository [4]. I have written this script so that eventually get the octal-base equivalent of 00, and store the value in the
it can run as a background process controlled by systemd (similar this_node variable. This is the RF24 network address of the
to the way you already set up the web application script earlier in Raspberry Pi.
this project). I will show you how to do this later, as first we must > In the next six lines, until the while block, the script will:
be sure the script runs properly on the command line. – start the RF24 radio;
– wait for 0.1 seconds for the radio to become ready;
The content of the function log_values() is an almost perfect – start the network at channel 90;
copy of the same function in script env_log.py that is already set – print the radio and network configuration to the console;
to run based on a Cron schedule. This function will simply receive – reset the packets_sent counter to zero;
sensor values as parameters and store them in the local database – and reset the last_sent counter to zero.
and Google Sheet on the Cloud. > Now the radio and network are ready, the script enters an
infinite loop during which it waits for a transition from an
Below I list and discuss selected elements of the script, in particular Arduino node.
those that relate to the RPI-nRF24 communications. > At the start of each loop, it calls the update() function [9] of
the network object. This checks for your messages.
> Right after the definition of the log_values() function, the > If there is no new message, the script goes to sleep for
script sets up the nRF24 module. It first initializes the radio 1 second. After this the loop restarts.
variable using the RF24 constructor. This constructor is part of > If there is a new message, the script uses the read() function
the RF24 Python wrapper library that allows us to use the RF24 [10] to read the 12 bytes (the payload) of the message, and pass
C driver from within our Python script. You can learn about them the payload variable. The read function will also get
WEB LINKS
[1] Gerber files for RF24 HAT board: https://techexplorations.com/parts/rpifs-parts/
[2] HAT PCB (unpopulated) from PCBWay:
www.pcbway.com/project/shareproject/Raspberry_Pi_Full_Stack_RF24_and_DHT22_HAT.html
[3] High-resolution version of schematic: https://techexplorations.com/parts/rpifs-parts/
[4] rf24_receiver.py script source code: https://github.com/futureshocked/RaspberryPiFullStack_Raspbian/blob/master/rf24_receiver.py
[5] See line 137 of RF24.h: https://github.com/nRF24/RF24/blob/master/RF24.h#L137
[6] See line 373 of RF24Network.h: https://github.com/nRF24/RF24Network/blob/master/RF24Network.h#L373
[7] Learn about ‘lambda expressions’ : https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions
[8] Learn about ‘int()’ : https://docs.python.org/3/library/functions.html#int
[9] Further info at : https://github.com/nRF24/RF24Network/blob/master/RF24Network.h#L413
[10] Further info at: https://github.com/nRF24/RF24Network/blob/master/RF24Network.h#L467
[11] Learn about ‘decode()’ : https://docs.python.org/3/library/stdtypes.html#bytes.decode
[12] Learn more about ‘split()’: https://docs.python.org/3/library/stdtypes.html#str.split
[13] Learn about ‘float()’: https://docs.python.org/3/library/functions.html#float
[14] Latest version of rf24_receiver.py: https://github.com/futureshocked/RaspberryPiFullStack_Raspbian/blob/master/rf24_receiver.py
[15] The project’s “home”: https://tmrh20.github.io/RF24/
Practical
ESP32 Multitasking (6)
Event Groups
Event flags
FreeRTOS defines 24 event flags for each Event Group object created
(Figure 1). These flags are represented in the C data type EventBits_t,
a 32-bit-wide data type of which 24 bits are available. Bit 0 is the least FCS FSD1
significant bit (LSB) of the available flags. The most significant 8 bits FSD0 FSD3
FSD2 FCLK
are reserved for internal use by FreeRTOS.
FSVP IO21
FSVN IO22
How these 24 bits are assigned and used by the application is left up IO25
MOD1 IO19
to the programmer. In this demo, the loop() task generates an event IO26 IO23
IO32 IO18
every second that results in two tasks synchronously starting differ- IO33 IO5
ing blink patterns via their associated LEDs. Bit 0 of the Event Group R1 R2 IO27
EN
IO10
(value 0b0001/decimal value 1) notifies a task named blink2() that IO14 IO9
220
220
IO12 RXD0
blinks LED1 twice. Bit 1 of the Event Group (value 0b0010/decimal IO13 TXD0
value 2) is assigned to notify a task named blink3() that blinks LED1 LED2 IO15
BOOT
IO35
Before we dive into the code, let’s review what the demo program GND GND
5V 3V3
hopes to accomplish. Two LEDs are driven by GPIO pins 25 and 26 USB
200274-001-94
(lines 5 and 6) in the active high configuration (see the schematic in
Figure 2). These GPIOs are configured in the setup() function as
outputs (lines 62 to 65). Task blink2() controls LED1 by blinking it
twice before waiting for the next event (lines 19 to 25). Task blink3() Figure 2: The schematic for the demo program evtgrp.ino.
controls LED2 by blinking it three times before waiting for the next event execution of the stalled tasks resume by returning from the called
(lines 41 to 47). Both tasks are identical, except for the number of times function. The event is triggered every second by a corresponding call
the blink loop is executed (lines 27 and 49) and the delay times used. to xEventGroupSetBits() in the loop() task (see lines 98 to 101 in
Listing 1 [1]).
Synchronisation
Synchronisation is achieved by having the task functions block in a Creating Event Groups
call to xEventGroupWaitBits(). Until the event is triggered, execu- The event group is created by calling xEventGroupCreate() (line 69).
tion stalls inside this function call. Once the Event Group is notified, There are no arguments to supply and the function returns a handle to
WEB LINKS
[1] Code for evtgrp.ino: https://bit.ly/35YrjCN
[2] W. Gay, “FreeRTOS for ESP32-Arduino”, Elektor 2020: https://bit.ly/2U2Yhg1
[3] FreeRTOS documentation: https://bit.ly/386HZL6
Synchronisation complete
This demo illustrates how two completely independent tasks, blink2()
and blink3(), can be synchronised using a single Event Group object. RELATED PRODUCTS
The loop() task broadcasts its event from lines 98 to 101. This approach
can be extended to up to 24 tasks if necessary (the limit is defined by
the number of event flags available in a single Event Group). While
> W. Gay, FreeRTOS for ESP32-Arduino, Elektor, 2020.
www.elektor.com/freertos-for-esp32-arduino
this article has shown one way to use Event Groups there are a whole
Advertisement
The elektor
investment program
Multi-Channel
Power Analyzer
Up to 3 Channels, with Graphic and Alphanumeric Display
By Wil Dijkman (The Netherlands)
When making voltage, current and power measurements on AC-powered devices things are
getting more complicated than measuring DC, because waveform and phase-shift between
voltage and current play an important role here. This instrument not only measures and
calculates quantities, but also shows waveforms and spectra of AC-signals on a graphical LCD.
This project was inspired by the AC/DC Power Meter published This means that the input and amplifier circuit need a complete
in Elektor Magazine in September 2015 [1]. At first I thought it was redesign. Also, a microcontroller is needed at the hot-side, to make
very interesting and I wanted to build one myself, but I found some automatic offset correction and auto-ranging possible. The block
limitations and drawbacks in this design, so I decided to develop an diagram in Figure 1 shows a main board and (up to) three satellite
“improved” design. Things I wanted to improve were: boards.
> The input circuit: It should be possible to measure current and The Main board
voltage independently: the current through the connecting leads The schematic (see Figure 2) is largely a copy of the EasyPIC V7 board,
should not influence the voltage reading. with a graphic LCD touch screen as user interface. A square wave
> The sampling rate: the low sampling rate makes it only possi- oscillator (circuit around IC1) generates a 12 Vpp square wave with
ble to measure the first eight harmonics of a 50 Hz signal (with a frequency of about 150 kHz for powering the satellite boards. The
perfect filter). This should be increased to the first 40 harmonics. data communication with the satellite boards will be via I2C, where
> The range switching and offset correction must be made the microcontroller on the main board is the master and the satellite
automatically. boards are the slaves.
The power supply section of the main board supports either a 12 V
stabilized or a 15...18 V supply without stabilization. The selection can
Satellite boards be made by a solder joint (SJ1). There are two other solder bridges/
jumpers: MAX1 and MAX2. With these, the number of channels can
V
be set for the master: closing MAX1 only means one, closing MAX2
I
Ch 1 means two and closing both means three channels (satellite boards).
V Power
I Some jumper wires (marked with Jx in schematics and on the main
I2C PCB layout) are used to avoid the need for a multilayer PCB.
V
I LCD + The Satellite board
Ch 2 mainboard touchscreen On the Satellite boards (schematic in Figure 3) I wanted to measure
V
I voltage and current independently. This is not fully realizable, but with
the circuit the low voltage input and the current input can float about
12V +/- 1 V with respect to each other. This is realized by the diode D3,
V
D4, D7, D8. Without measures taken, the circuit can be damaged by a
I
Ch 3 wrong connection: the high potential to the low voltage input and also
V
I the current input at the low voltage side. To prevent this damage, the
circuit with T10…T14 and reed relay K1 is added. A first current limita-
tion is realized by R11: at 750 V input voltage the maximum current is
Figure 1: Block diagram of the Power Analyzer. 0.5 A. If the current through R11 is larger than some 10 to 20 mA, there
2M7
SIGOFF
GNDOFF
VX25
VOFS
R2 R12
VX5
2M7
2M7
G G
C6
R19 IC2 1n8
3
V-HIGH 270 R15 R16 R17 R18 IC4
D S D 1 3
T1 T2 OPA170 274 274 12k 12k R20
4 1
0.1% 0.1% 0.1% 0.1% OPA170 100
C4 4
R13 0.1%
R14 0.1%
1n8
12k R25 0.1%
0.1%
1k
12k TP1
1k5
IC5
R24
R22 D D
C5 4
D1 C9 D2 SJ3 C8
T4 T3 470p 1 C11
1k43
OPA170
0.1%
3 470p
12n 82n
1k5
G G
R23
C10
BAS316 BAS316 S S 470p
R26 0.1%
V-LOW G G 12k
R11 T1...T8 = BSH105 C12
T6 T5 IC6 1n8
G G
1k5
D D 4
R27 R28 R32
1
R29 OPA170 274 274 12k
D S D
3 0.1% 0.1% 0.1%
270 T8 T7
K1
VRP R100
3 9
R35 R39
C39 D5
BAS316
470
18k
T11 C13
GPA1603 GPA1603 BC858C R42
220
R41
T13 R36 5 5 5 5 100n
2k2
100n R72
4n7
GPA1603 GPA1603 150 VRM
C22
R60 IC8 1n8
3
I-LOW 1k R53 R54 R55 R56 IC9
1 3
OPA170 274 274 12k 12k R58
4 1
0.1% 0.1% 0.1% 0.1% OPA170 100
C18 4
R51 0.1%
R52 0.1%
T16...T23 = BSH105 1n8
12k R65 0.1%
0.1%
1k
12k TP3
1k5
IC10
R64
R62 D D C21 4
D9 C27 D10 SJ4 C23
0 0065
C24
1k5
S S
R63
G G
IOFS
IX25
SIGOFF
IX5
R48
10 VRP
R1
TP7
100
IC1 = TL431
R21
1
R6 R5 IC3 R8
12k
12k
IC1 1
C19 C2 3 5
R3
0.1% 1
4 7 OPA170 1
100n 4
16V R9 C7 C3 C1
15k
12k
R10 4 7 4 7 4 7
0.1% 16V 16V 16V
6
5
4
3
2
1
10k
3 9
JP1 PICKIT
R89 R90 R75 R74 R79 R80
C16
10k
10k
1k5
1k5
20
100
100
100n VDD
1 21
MCLR/VPP RB0/INT0
22
IC13 RB1/INT1
2 23
RA0/AN0 RB2/INT2
3 24
RA1/AN1 RB3/CCP2
4 25
RA2/AN2/VREF- RB4
5 26 R81 R88
RA3/AN3/VREF+ RB5/PGM C31
6 27
RA4/T0CKI RB6/PGC
1k5
1k5
7 28 IC14
RA5/AN4/SS/LVDIN RB7/PGD 100n
1 8
PIC18(L)F26K80SOIC VCC1 VCC2
11 15 2 7
RC0/T1OSO/T1CKI RC4/SDI/SDA OUTA INA
12 16 3 6
RC1/T1OSI/CCP2 RC5/SDO TP8 INB OUTB
13 17 4 5
RC2/CCP1 RC6/TX/CK GND1 GND2
14 18
RC3/SCK/SCL RC7/RX/DT
ISO1540 R77
10 9
OSC2/CLKO/RA6 OSC1/CLK1 X1
3 9
5 6
VSS VSS
3 4
SJ1 SJ2 8 19
C32 1 2
4 7
16V
VRP
T24
R82
10k
T25
R102 R83
SIGOFF
10k 10k
T26
R103 R84
GNDOFF
10k 10k
T27
R85
VX25
10k
T28
R86
VX5
10k
T29
R87
IX25
10k
IX5
R91 R92 R93 R94 R95 R96
C41 C40 T24... T29 = BC858C
10k
10k
10k
10k
10k 10k
100n 100n
VRM
D12 R98 C37
VOFS
1M5
BAS316 100n
12k
T9
BSH105
C15 100
R37
35V PMEG3020EH
C35
1k
R46
1n
1000 R45 R97
12k
16V
TR1
47
120
IC7
TL431
C34
R49 R57
1k
12k
100p
BC858C
T15
R59 C25
C36
1k
1n
1000 R61 R70
16V C20
D11
12k
330
IC11 100
TL431 R73 35V PMEG3020EH
VRM 47
TP6 190133-012
2k2
6
1000
16V 5
R38 R39 R34
R35 4
R3
10k
10k
10k
J5
100
R2 2k2 C2 3
D 2
3 9
T1
D1, D2 = PMEG3020EH 100n R41 R40
R4 1
3 9
3 9
100
G +5V
D
T2 C24 C23 +12V-IN
S BSH105
R14
100n 100n R7
3 9
C3 G R9 7 28 R15
S C4
100n VDD VDD
120
C8 10k
10k
BSH105 30 17 R36
R6 1 8 RA7 RB7 100
10k DT GD1 100n 31 16 R37
IC1 R10 RA6 RB6 100 100n R11
R8 2 RT 7 24 15
1k5 VCC RA5 RB5
J12
120
0
D 23 14
3 6 RA4 RB4
OC GND T3
22 11 J11
C7 R12 RA3 RB3
C5 4 SS
UCC25600 5 G 21 IC5 10 J10 R16
GD2 10 RA2 RB2
100n C6 20 9 J8
100n RA1 RB1
120
R13 S MAX1 MAX2
BSH105 J6
10k
19 8
RA0 RB0
470p
D2 R18
120
18
MCLR
+5V 27
RE2
RD0
RD1
RD2
RD3
RD4
RD5
RD6
RD7
26
RE1
25
RE0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
PIC18(L)F46K22TQ
R/W
J1
RST
VEE
VO
VCC
D0
D1
D2
D3
D4
D5
D6
D7
GND
CS1
CS2
RS
LED-
LED+
X1
1 2
1 5 RD7
3 4 RC7 RD7
44 4 RD6
C9 5 6 RC6 RD6 TP4
43 3 RD5 X2
1 RC5 RD5 TP3
J9 42 2 RD4 Y2 LCD1
X3 RC4 RD4 TP2
1 2 J7 37 41 RD3 X1
RC3 RD3 TP1
3 4 36 40 RD2 Y1 Mikroe-240SMT
RC2 RD2
C14 5 6 35 39 RD1
RC1 RD1
1 32 38 RD0
RC0 RD0
X4
1 2 VSS VSS
R17
3 4 3 9 +5V 29 6
C18 5 6
1
R7 R20 R19
C13
1k
1k
1k
100n T4
R21 +12V-IN +5V
10k
T5
R22 L78M05ACDT
10k BC858 R24
BC848C 3 9 IC3
J2 T6 X2
R23
10k L1 150 H SJ1
T7 R26
R25 C17 IC2 330n 330n
100k
J3 10k
100n
BC848C T8 R30 C10 C11 C12
R29 C19
100k
10k
100n 330n 330n
100n
L2 150 H
BC848C
190133-011
Unfortunately I forgot some decoupling capacitors in the supply part, cies there is no problem. Signals with less than three zero-crossings
these had to be added too. The part list for this project in Open Office during the sampling period are treated as DC.
format can be downloaded from [2]. Order codes for Farnell are given,
but of course you can choose any supplier. The second question is how many samples will be taken in these
35 ms. A sampling frequency of 10 kHz or higher would be ideal. I have
Software for the satellite board chosen for 357 samples at 10.2 ks/s. This leads to a integer multiple
The program is written in mikroBasic for PIC (V5.6.1) from MikroElektronika, of samples for 50 and 60 Hz signals. These frequencies can then be
a programming language that is relatively easy to understand. analyzed with the highest accuracy.
I wanted that a frequency range from (a bit) less than 50 Hz to a few
hundreds of Hz could be processed. Therefore, the signal needed to There is a library with I2C commands in mikroBasic, but these are only
be sampled for at least 30 ms. Then, at 50 Hz there are at least three for an I2C master. For an I2C-slave I had to write my own procedures.
zero-crossings, so you can detect one period. But that is only true when These procedures are needed to setup and control the communi-
these zero-crossings are equidistant. With a duty cycle unequal to 50 % cation with the main board, the I2C master. The latter just requests
at 50 Hz, 30 ms is not sufficient, that’s why I have chosen for 35 ms. and displays information from the satellite boards, (auto-) ranging
Then with a duty-cycle of less than 25 % there it is possible that the and offset, all signal processing, including sampling and filtering is
frequency is not correctly determined at 50 Hz, with higher frequen- performed on the satellite board(s).
Figure 4c: One of the extra support brackets between front panel and cover. Figure 4d: PE-connection
Fast Fourier transforms are also calculated on the satellite boards. The how the units are fixed in the case. Note the ready-made, standard
calculations are not invented by me but “borrowed” from [3]. Digital power supply that is used to power the Power Analyzer.
filtering is based on chapter 16 of The Scientist and Engineer’s Guide
to Digital Signal Processing [4]. A Blackman-window is used and the Figure 4c shows one of two extra brackets, which are added to prevent
filter has 13 coefficients (M=12). The choice of the length of the filter is the front panel from bending when test leads are plugged in or out. An
a compromise between calculation time, memory needed and perfor- extra hole in the top and bottom cover must be drilled to attach the
mance (i.e. suppression of signals above 2.55 kHz and attenuation of brackets. I used a metal housing so the enclosure must be connected
signals below 2.55 kHz). to the mains Protective Earth, see Figure 4d.
Assembly Operation
A front panel has been designed for a three channel version, which After switching on, the measurement screen appears. It displays some
can be ordered at Schaeffer’s. I used a metal case (order code 1510827 units and their values for the channel that is selected. At the top of the
at Farnell, manufacturer Metcase, M5503110). screen you can select other channels (if available).
Figure 4 shows some detailed pictures of the hardware in this enclo- The screen can display a maximum of seven measurement values,
sure, giving an impression of what the Power Meter can look like and selected in the Configuration Screen.
First go to the Main Menu (top right of the screen). Choose Configuration you go back to the Measurement Screen, the chosen formula with
and then the Configuration Screen appears with 16 values to choose the calculated value is displayed for all channels.
from. The selected values to be displayed are highlighted.
Back in the Configuration Screen you can also choose for Graphs->
Some of these values will go without saying, but some need explana- Pressing this you can choose between Scope or FFT. Press Scope. This
tion. Vdis and Idis (distortion) are calculated using: brings you to select traces. Trace1 will always be displayed. A selected
trace will be high-lighted. All traces can be “connected” to a channel
40 and to V, I or P of that channel. The display will be “triggered” by a
∑V n
2 positive zero crossing of Trace1. The display will give you an impres-
sion of the wave shape of the signals and their phase relation. Two
n=2
Vdis =
V1 periods of the signal will be displayed. The amplitude of the signals
is always the same: voltage signals have the maximum amplitude. To
distinguish them from voltage signals, current signals are displayed
where VN stands for the amplitude of harmonic N of the signal. with a 80 % and power signals at 60 % amplitude. See for example
Re-P means real power, P-VA means Vrms x Irms, Im-P means imagi- the waveforms of a transformer which goes in saturation in Figure 6.
nary power, and PF means power factor, i.e. Re-P / P-VA. The scope display doesn’t show absolute values, it’s just an indication
If you choose Eff-> you enter the Efficiency Screen. Here you can of shape and phase relation.
choose the formula which describes the power relation that you are
investigating and then you go back to the Configuration Screen. If Back in the Graphic Screen, press FFT. This shows the FFT compo-
nents of a selected signal. On top of the screen you can select the
channel, LINear or LOGarithmic display and either V or I. The largest
harmonic (usually but not necessarily the first harmonic) is displayed
at 100 % or 0 dB. The horizontal scale gives the number of the harmon-
BUILDING THE TRANSFORMER ics, not its frequency.
Transformer TR1 is home made. Here is the recipe.
When entering the Logging feature, you must first select the time
Ingredients (mentioned at the bottom of the parts list): two period that you want to apply. Possible values are between 0.25 h
core halves, two clips, one coil former, all for EF20, wire with and 128 h in steps of a factor of 2. Next step is to select how many
900 V isolation and diameter of max 1.3 mm. traces you want to log (maximum three). Each trace can be linked
to a channel and from that channel you can choose either V, I or P.
> Take the coil former and cut off pins 2, 3, 4, 7, 8 and 9. Pressing Continue immediately starts the logging. An alphanumeric
> With the wire make 9 turns between pin 1 and 10. You shall screen will be shown, where you can watch the average, maximum
exactly fill one layer. and minimum value and the elapsed time. You can also go to the
> Repeat to make 9 turns between pins 5 and 6. Again you graphical screen. At the top of the screen you can select another
shall exactly fill one layer. trace, if it is switched on. Pressing Return brings you back in the
> Put in the core halves and put on the clips. There is no air main screen, the collected data are lost.
gap.
> If everything went well, you will have a transformer with an You can select Crest factor (V-CF or I-CF) in the configuration screen.
equal primary and secondary inductance of about 125 µH. It simply divides the highest peak value (positive or negative) by the
Capacitance between primary and secondary will be in the RMS-value of the signal. Remember that the bandwidth of the measur-
range of 30 pF. ing amplifiers is 2.5 kHz, so this function is not suitable for audio. Only
until, say 250 Hz depending on your taste.
How to calibrate and adjust When done calibrating a channel, press ->OK. Then the calibration
From the Main Screen you can go to the Calibration screen. You can data are stored on the satellite board of the selected channel.
choose between calibrating the touchscreen and calibrating the
channels. At the first start up the touchscreen calibration procedure As far as I’m concerned this project is finished. There will be no more
will automatically be presented. Use a pencil or wooden stylus to large additions or changes. But of course, I will answer any question.
calibrate (and use) the touch screen.
This article is based on the information presented on the Elektor Labs
In the channel calibration you will first be prompted to select a channel. project page at [2]. On this page, more detailed information on this
Then the software enters a screen where voltage, current and frequency Power Analyzer including software, PCB design files and BOM can be
can be measured and adjusted. In this screen the automatic ranging found or downloaded. The Eagle CAD-files on Elektor Labs are up to
for V and I is disabled, which will make it easy to adjust the calibration date with the most recent changes, but newer versions of the PCBs
for each range. With the arrows (< and >) you can change ranges and have not been built and/or tested!
adjust the measured value. 190133-B-01
The best method to adjust the frequency is to connect a digital oscil-
loscope to TP8 (signal) and TP2 (GND) on the satellite board of the Contributors
selected channel. Adjust the visible pulse width to 35.00 ms with Idea, Design, Text and Illustrations: Wil Dijkman
the arrows on the frequency line. Second best method to adjust the Schematic: Patrick Wielders
frequency is to use a signal source with a calibrated frequency of 50 Editor: Luc Lemmens, CJ Abate
or 60 Hz and adjust the reading to 50.00 or 60.00 Hz. The reading Layout: Giel Dols
can vary ±0.5 %.
Questions or comments?
Do you have questions or comments about his article? Email RELATED PRODUCTS
the author at w.j.dijkman@onsbrabantnet.nl or contact Elektor
at editor@elektor.com > Microcontroller Basics with PIC
www.elektor.com/microcontroller-basics-with-pic
WEB LINKS
[1] AC/DC Power Meter: www.elektormagazine.com/magazine/elektor-201509/28070
[2] Power Analyzer: www.elektormagazine.com/labs/power-analyzer
[3] FFT calculation: www.nicholson.com/dsp.fft1.html
[4] The Scientist and Engineer’s Guide to Digital Signal Processing, by Steven W. Smith, Ph.D.: www.dspguide.com/pdfbook.htm
Analogue
Filter Design (Part 3)
Passive Filters
By Alfred Rosenkränzer (Germany)
The third and final part of this series on the design of analogue filters deals with the
subtleties of passive filters. Since only purely passive components such as resistors, coils
and capacitors are used here, amplification is not feasible. Thus high input and low output
impedances cannot be realised. However, high frequencies in the three-digit MHz range and
above are less problematic.
The input impedance of active filters can be made very high by about the correct ‘termination’ or the matching of impedances at
adding a buffer at the input; a buffer at the output can make the the input and the output. However, passive filters are often still used
output impedance very low. As a result, we no longer need to worry at very high frequencies. These are designed for specific input and
R2 R2 R2 R2
C1 L1
2. Order
R1 R1 R1 C1 R1 C1
L1 L1
R2 R2 R2 R2
C1 C1 L1 L1
3. Order
R1 L1 R1 L1 L2 R1 C1 R1 C1 C2
R2 R2 R2 R2
C1 C2 C1 L1 L2 L1
4. Order
R1 R1 R1 C1 C2 R1 C1 C2
L1 L2 L1 L2
R2 R2 R2 R2
C1 C2 C1 C2 L1 L2 L1 L2
5. Order
R1 L1 L2 R1 L1 L2 L3 R1 C1 C2 R1 C1 C2 C3
R2 R2 R2 R2
C1 C2 C3 C1 C2 L1 L2 L3 L1 L2
6. Order
R1 R1 R1 C1 C2 C3 R1 C1 C2 C3
L1 L2 L3 L1 L2 L3
R2 R2 R2 R2
C1 C2 C3 C1 C2 C3 L1 L2 L3 L1 L2 L3
200522-001
Figure 1: Basic schematics for passive low-pass and high-pass filters with PI and T structures from first through to sixth order. Both the corner frequency and
the frequency characteristic depends on the component values. The structures shown here are suitable for Bessel, Butterworth and Chebyshev filters.
R1 L1 R1 C1
C1
L1
R2 R2
R2 R2
C1 C2 L1 L2
L3
C3
4. Order
C3 L3
R1 L1 L2 R1 C1 C2
R1 R1 C1 C2
L1 L2
C1
L1
R2 R2
R2 C2 R2 L2
C1 C2 L1 L2
L3
C3
5. Order
C4 C5 L4 L5
R1 R1 C1 C2 C3
L1 L2 L3
R1 R1 C1 C2
L1 L2
C1 C2
L1 L2
R2 R2
R2 R2
C1 C2 C3 L1 L2 L3
L4 L5
C4 C5
6. Order
C4 C5 L4 L5
R1 R1 C1 C2 C3
L1 L2 L3
R1 L1 L2 L3 R1 C1 C2 C3
C1 C2 C3
L1 L2
R2 R2
R2 R2 L3
C1 C2 C3 L1 L2 L3
L4 L5 L6
C4 C5
200522-002
Figure 2: Basic schematics for low-pass and high-pass filters of third through to sixth order with Cauer or inverse Chebyshev characteristics in PI and T
configurations.
output impedances (which do not have to be identical). It should Figure 2 shows the basic structure of Cauer (elliptical) and inverse
be noted that deviations from the expected source or load imped- Chebyshev filters (also known as type 2). Here the inductors or
ance can have a strong influence on the filter characteristic. In capacitors are replaced with parallel or series resonant circuits.
this article we will take a look at the types of passive filters that Drawn are low- and high-pass filters in PI and T configurations
are commonly used and what needs to be considered. from the third through to sixth order.
Structures Figure 3 shows the basic structure of band-pass and band-stop
In Figure 1 you can see the basic structure of high- and low-pass filters with a Bessel, Butterworth or Chebyshev characteristic (from
filters of the first through the sixth order. By choosing the correct third through to seventh order), and in Figure 4 we see the more
values for the components, these structures allow filters with Bessel, complex structures with Cauer and inverse Chebyshev characteris-
Butterworth and Chebyshev characteristics to be realised. You can tics (fifth and seventh order). Here too there are PI and T variants.
choose whether a filter starts with a component in series with the
others (T-structure) or with a component to ground (PI-structure). Dimensioning
A Bessel or Butterworth filter is entirely determined by the filter
In the leftmost column of Figure 1 are the PI low-pass filters that characteristic, the -3dB corner frequency, the chosen structure, the
all begin with a capacitor to ground at their inputs. In the second order, and the input and output impedances. In contrast to the active
column are the T low-pass filters that start with an inductor in series. filters, with passive filters there is no freedom at all when it comes to
choosing component values. If you would like to select, for example,
The high-pass filters are exactly the other way around. In the third a standard value from an E-series for an inductor, then you will have
column we see the PI high-pass filters with an inductor to ground to adjust the corner frequency of the filter at a given impedance a
and, in the rightmost column, the T high-pass filters with a capac- little. Of course this is only possible if the application allows it.
itor in series.
How the characteristics of a Butterworth filter change for the differ-
At the higher orders components are added alternating between ent orders has already been discussed in part 1 of this series [1]. Now
longitudinal (in series) and transversal (to ground). These additional we can see how the component values change depending on the
components have different values than the first components. For chosen corner frequency. In Figure 5 we see the fully dimensioned
the desired functionality it does not matter whether we choose schematic of a fifth-order Butterworth low-pass filter with a corner
a T or PI structure. But, because inductors are not popular with frequency of 1 MHz. If we want to double the corner frequency
electronics designers, it is common to attempt to use as few of to 2 MHz we only need to halve the values of the inductors and
these as possible. the capacitors. This is no surprise because the corner frequency
R1 L3 R1 C1 C2
L1 L2
R2 R2
C1 L1 C2 L2 L3 C3
5. Order
C4 C5
R1 L4 L5 R1 C1 C2 C3
L1 L2 L3
R2 R2
C1 L1 C2 L2 C3 L3 L4 C4 L5 C5
7. Order
C5 C6 C7
R1 L5 L6 L7 R1 C1 L1 L2 C2 L3 C3 L4 C4
R2 R2
C1 L1 C2 L2 C3 L3 C4 L4 L5 C5 L6 C6 L7 C7
200522-003a
3. Order L3 L1 L2
R1 C3 R1 C1 C2
L1 L2 L3
R2 R2
C1 C2 C3
5. Order
L4 L5 L1 L2 L2
R1 C4 C5 R1 C1 C2 C3
L1 L2 L3 L4 L5
R2 R2
C1 C2 C3 C4 C5
7. Order
L5 L6 L7 L1 L2 L3 L4
R1 C5 C6 C7 R1 C1 C2 C3 C4
L1 L2 L3 L4 L5 L6 L7
R2 R2
C1 C2 C3 C4 C5 C6 C7
200522-003b
Figure 3: Basic schematics for band-pass filters and band-stop filters of third, fifth and seventh order with Bessel, Butterworth or Chebyshev characteristics
using PI and T structures.
is proportional to 1 / √(L * C). That is why, in the era before pocket Now that we are on the subject of impedances we can also take
calculators and PCs, it was easy to convert a basic schematic with a look at the effect an incorrect source or load resistance has. As
a given corner frequency to the desired design frequency. If the an example we connect a filter that has been dimensioned for an
standard impedance of 50 Ω remains the same then the resistor impedance of 100 Ω to a source with a 50 Ω impedance. It is also
values, of course, also remain the same. terminated at the output with a 50 Ω impedance. Figure 6 shows
the frequency characteristic in the pass band.
It is also interesting to see how the component values behave when
a filter is redimensioned for other impedances. This is also possi- Returning to the topic of dimensioning, with a Chebyshev filter
ble without the help of a computer. If we would like to double the the ripple in the pass-band is an additional parameter. The effect
impedances in the 1 MHz low-pass filter in Figure 5 from 50 Ω on the frequency response can be seen in Figure 7. Here we see
to 100 Ω then we only have to double the values of the inductors the amplitude responses of a seventh-order 1 MHz Chebyshev
and halve the values of the capacitors. Again, this is not a surprise, low-pass with a ripple of 0.1 dB, 0.5 dB, 1 dB and 3 dB in the
because Z is proportional to √(L/C). pass-band. The more ripple allowed, the steeper the curve in
R1 L3 L4 R1 C1 L1 L2
C2
L3 L4
R2 R2
C1 L1 C2 L2
C3 C4
7. Order
C4 C5 C6 C7
R1 L4 L5 L6 L7 R1 C1 L1 L2 C2 L3 C3
L4 L5 L6 L7
R2 R2
C1 L1 C2 L2 C3 L3
C4 C5 C6 C7
200522-004a
R1 C3 C4 R1 C1 C2
L1 L2 L3 L4
R2 R2
C1 C2 C3 C4
7. Order
L4 L5 L6 L7 L1 L2 L3
R1 C4 C5 C6 C7 R1 C1 C2 C3
L1 L2 L3 L4 L5 L6 L7
R2 R2
C1 C2 C3 C4 C5 C6 C7
200522-004b
Figure 4: Basic schematics for band-pass and band-stop filters of fifth and seventh order with Cauer or inverse Chebyshev characteristics in PI and T
configurations.
the stop band. How much ripple we can allow depends on the other filters, but the point where the curve drops below the defined
application. amount of ripple. If you would like to normalise the curves to the
-3dB point, in order to compare them better, you will have to adjust
In Figure 8 we have enlarged the pass-band from Figure 7. Here the corner frequency accordingly.
we can see that the corner frequency is not the -3dB point, as with
R1 L1 L2
50
12 87 12 87
R2
C1 C2 C3
50
200522-005
With the Cauer filter the minimum attenuation in the stop band
C1 C2 C3 is another additional parameter. The notches provide a much
steeper transition in the stop band, but the curve then returns
L1 1n10
R1 6n56 4n27
L2 L2
50 to a lower attenuation. The number of notches corresponds to
7 90 3 38 4 37
C4 C5 C6 C7
R2 the number of resonant circuits in the circuit (as these have
different frequencies). Figure 9 shows a seventh-order Cauer
50
Figure 10: Frequency responses of seventh-order, 1-MHz Cauer low-pass Figure 11: Close-up of the pass-band from Figure 10 with a minimum
filters with a minimum attenuation of 40, 50, 60 and 70 dB. attenuation of 40 dB (brown), 50 dB (blue), 60 dB (green) and 70 dB (red).
minimum attenuation. You can see the different slopes of the the filters had to be tuned by hand using a network analyser. There
curves in the transition region and the accompanying minimum aren’t many filter programs that can compute the complete filter.
attenuation. But this also changes the frequency of the notches. The increasing amount of digitisation (also in video technology),
If you would like to filter out a fixed interference frequency from a along with higher clock speeds and oversampling in DACs and
signal, you could tune such a notch to that frequency by adjusting ADCs, means that there are not the same high demands on analogue
the corner frequency or the minimum attenuation. With this you filters as there used to be. This means we can now do without the
have to keep a close eye on the tolerances of the components and compensation for group delay. Figure 14 shows the circuit of a
therefore the exact position of the notches. The enlargement of passive, second-order all-pass filter and, in Figure 15, we see the
the frequency response in Figure 11 shows that the ripple in the corresponding characteristic of the group delay.
pass band is 0.5 dB for all filters.
Now an excursion into practice: in Figure 16 you can see a DIY video
The final filter characteristic is the inverse Chebyshev (IT). This looks filter using Neosid inductors (the copper-coloured, square components
like a Butterworth filter in the pass band and therefore has no ripple, with a tuning core). The two coils on the left are part of a fifth-order
so this parameter is omitted. But in the pass band the IT characteristic Cauer low-pass filter. The block of six coils are part of an all-pass filter.
looks more like that of a Cauer filter with notches and an accompany- Each time there are multiple capacitors connected in parallel in order
ing minimum attenuation. The basic schematic is the same as that to realise the necessary ‘awkward’ values. The round, blue components
for the Cauer filter (Figure 9) and only the dimensioning is different. are KP capacitors in the nF range with a tolerance of 2%.
Figure 12 shows the frequency response of the inverse Chebyshev
filters with a minimum attenuation of 50, 60 and 70 dB. Figure 13 is Unusual filters
a zoomed-in view of the pass-band of the characteristic of Figure 12. The filters that we have discussed so far are ‘single ended’: they
operate with single-ended signals with respect to ground. But it is
All-pass filters also possible to build passive filters for differential signals.
In analogue television technology there was (once) the need for
steep filters, but the large overshoot of the step-response brought Differential filters
about strong interference signals. That is why the group delay was Modern ADCs and DACs for high signal frequencies have differen-
‘pepped up’ using all-pass filters. This took quite a bit of effort and tial inputs and outputs. It is therefore obvious that the necessary
Figure 12: Frequency responses of the inverse Chebyshev filters with a Figure 13: Close-up of the pass-band of Figure 12 with a minimum
minimum attenuation of 50, 60 and 70 dB. The colours are self-explanatory. attenuation of 50 dB (blue), 60 dB (green) and 70 dB (red).
R1 272p
L1
50
1 98
C2 C3
50
L2
The circuit in Figure 17 consists simply of two identical 10 MHz
1 18 Butterworth low-pass filters of the fifth order in a conventional
single-ended design. The signal paths have no shared compo-
200522-014 nents (except ground) so component tolerances can cause differ-
ent behaviours in the two ‘channels’.
Figure 14: Schematic of a passive all-pass filter of the second order.
The second variant, in Figure 18, looks more like a real differential
filter, but here each of the two capacitors from Figure 17 that were
connected to ground are now combined into one. They therefore
now affect both signal paths in equal amounts. In this case differ-
ences can only occur because of the inductors.
For differential or push-pull signals, both these circuits exhibit
the same filter operation. But for common-mode signals the filter
behaviour is different. Figure 19 shows that, in the combined filter
of Figure 18, only the inductors influence the frequency response
and that, therefore, there is only a weak filter effect for common-
mode signals. Although the common-mode signals from DACs are
reduced by the differential amplifier that follows, this is not optimal
because the common-mode rejection of RF amplifiers reduces as
the frequency increases. Every solution always has its advantages
and disadvantages. To realise filter stages that are as identical as
possible we can, for example, use filter modules from the same
production batch so that the filters are as identical as possible.
Double-inverse fourth-order Chebyshev filter
Figure 15: Characteristic of the group delay of the second-order, passive
all-pass filter in Figure 14. I noticed this filter when reverse-engineering a filter that I had
bought. It consists of two fourth-order filters joined together
(Figure 20) and has a nice characteristic that can be easily realised
with components from the standard E-series. It also requires few
‘awkward’ values, making building it much simpler. If you would
like to change the corner frequency of the filter, then you can
change the values within the standard E-series. This advantage
is however at the cost of a small dip in the pass-band. Figure 21
shows the frequency response of this filter, which has an impres-
sive minimum attenuation of 70 dB in the stop-band. Both notches
have the same frequency and reinforce each other. In Figure 22
we have enlarged the response in the pass-band where we can see
the characteristic dip at 75 MHz.
Figure 16: DIY video filter with eight Neosid inductors.
R1 L1 L2 R1 L1 L2
50 50
1 29 1 29 1 29 1 29
R2 R2
C1 C2 C3
50
50
50
Figure 17: Combination of two ‘normal’ Butterworth low-pass filters to filter a Figure 18: This variant combines the capacitors Cx and Cx’ into one
differential signal. capacitor with half the value of capacitance that, in Figure 17, were each
connected to ground individually.
on the circuit board. You can admire this in the filter of Figure 23,
50
47p 47p 47p
although the third inductor at a relative angle of 45° is not really in
a optimal position. In the filter of Figure 24 the small blue induc- 200522-020
tors are not connected in series and there are also no capacitors
connected in parallel. The manufacturer probably has these compo-
nents specially manufactured so that they fitted perfectly. Figure 20: Double inverse Chebyshev filter of the fourth order.
A possible way out of the problems with inductors is the use of
adjustable versions. Here you can change the self-inductance within
certain limits by turning the ferrite cap or core. This is, for example,
the case with the Neosid inductors that are used in Figure 16.
There is something else that needs to be taken into account with
inductors: the windings have an ohmic resistance that often cannot
be ignored. We have to measure this or find it in the datasheet and
carry that over into the simulation when dimensioning the filters.
The non-ideal behaviour of the inductors, as a consequence of the
resistance of the windings, can lead to a reduced frequency response
in the pass-band. This has to be either corrected or compensated
for in the circuit that follows.
In general, larger inductance values use coils with ferrite cores that
act as a kind of ‘amplification’ compared to the self-inductance
of the winding on its own. Depending on the size of the core, the
number of turns, and the size of the current that flows, the core
can become magnetically saturated and therefore generate an
enormous amounts of distortion. If more harmonics are measured
at the output of a filter than at the input, the signal level should Figure 21: Frequency response of a fourth-order double inverse Chebyshev
be reduced or inductors with larger ferrite cores should be used. filter.
Questions or Comments?
Do you have any questions or comments related to this article?
Then email Elektor at editor@elektor.com.
Contributors
Idea, circuits and text: Translation: Arthur de Beun
Alfred Rosenkränzer Editor: Stuart Cording
Schematics: Patrick Wielders Layout: Giel Dols
RELATED PRODUCTS
Layout
In addition to the already mentioned zigzag pattern for the arrange- > OWON SDS1102 2-ch Digital Oscilloscope (100 MHz)
ment of inductors, you have to ensure short, direct connections www.elektor.com/owon-sds1102-2-ch-digital-oscilloscope-100-mhz
to ground. Double-sided printed circuit boards with one side for
signals and one side for ground make this much easier. Especially > Siglent SDG2042X Arbitrary Waveform Generator
at higher frequencies, and therefore lower capacitance, you must (40 MHz)
not forget that the solder pads themselves act as little capacitors www.elektor.com/siglent-sdg2042x-arbitrary-waveform-generator-40-mhz
with respect to ground. If this is relevant you will need to take
> OWON XSA1015-TG Spectrum Analyser
these ‘parasitic’ capacitors into account when selecting the value
(9 kHz – 1.5 GHz)
of the capacitor. www.elektor.com/owon-xsa1015-tg-spectrum-analyser-9-khz-1-5-ghz
200522-04
WEB LINKS
[1] “Analogue Electronics Design - Part 1: Analogue filter theory”, Alfred Rosenkränzer, Elektor September/October 2020:
www.elektormagazine.com/magazine/elektor-155/58969
[2] LC Filter Design Tool: https://rf-tools.com/lc-filter/
[3] AADE: https://getwinpcsoft.com/Filter-Design-179557/download/
[4] Quickfil 5.1 (DOS program): www.omicron-lab.com/products/vector-network-analysis/quickfil/
[5] Simetrix: www.simetrix.co.uk
JOY-iT VAX-1030
Wireless Measurement Module
By Harry Baggen (Elektor)
Display
There are two options for linking the display module to the
measurement module. You can use the included USB cable to
connect it directly to the measurement module or you can use the
built-in wireless connection. A wireless connection is established
automatically if the USB connection is not available. According
to the manufacturer, several modules can be used at the same
time with up to 26 channels possible simultaneously. Obviously,
when using the wireless connection, the display module must be
provided with its own supply voltage. This can be achieved using
the micro USB port (5 V) or via a two-way JST connector (8–16 V)
for which a matching cable is included.
Figure 2: The measurement module with the top cover unclipped.
The display measures approximately 3 × 2.5 cm and is very bright, so
it is easy to read even under high ambient light conditions. There are
three touch-sensitive buttons next to the display. By default the display
shows the measured voltage and current together with the time at
A lot of current the start of the measurement cycle. A battery icon can be displayed
The version described here is suitable for DC voltages of up to 100 V on the left to indicate the remaining battery capacity after a nominal
and currents of up to 30 A. There is also a version that can handle battery capacity has been entered. The connection mode, relay state
up to 100 A but, unless you want to make measurements on car and measured temperature are shown at the top of the screen.
batteries or the like, 30 A should be enough in most cases. The
measurement module consists of a small plastic box with several Even more information appears when you touch one of the buttons.
openings in the cover. These allow you to connect the cables and This adds the display of the supplied or consumed power beneath
the power supply to the screw terminals inside the box. the voltage and current. In a further, smaller area you can see how
many ampere-hours the power source or battery has supplied, the
The internals of the box consist of a sandwich of two PCBs number of watt-hours, and the elapsed usage time. On the right there
(Figure 2). The top PCB holds all the screw terminals and a large is a list with a number of menu items that you can scroll through
relay while the bottom PCB contains the control circuitry and a with the up and down keys. We cover these in more detail shortly.
2.4 GHz transceiver module for wireless communication with the
display module. It looks a lot like an ESP8266 WiFi module but, Potential applications
as the chip is hidden beneath a drop of glue, we can’t be sure. The This set of display and measurement modules can be used for
top part of the enclosure can be easily unclipped to provide good various purposes. For example, you can measure the current
access to the screw terminals. suppled to a load by a power source. If the power source is a battery
DC 12V DC 12V
+ – + – + – + –
Power Load Battery Charger
Source
Figure 3: The load on the output can be replaced by a battery charger. Measurements can be made in both directions.
(primary or rechargeable), you can use this to keep track of how user guide instructions for this module. A little bit of searching
many ampere-hours it has supplied. You can also work in the revealed that it is used for selection of the external 12 V supply
opposite direction, with the load replaced by a battery charger. voltage. In the 3W position an external 12 V supply is necessary
This then shows how much energy has been supplied to the battery for operation of the measurement module. In the 2W position the
(Figure 3). module can derive this voltage from the connected power source,
as long as the voltage is between 10 V and 30 V. The module tested
There are a number of menu settings that are especially interesting functioned down to 8 V.
for use with rechargeable batteries. For example, the upper and
lower limits for switching off the relay can be defined. This can be The wireless connection is very convenient for keeping an eye on
used to avoid deep discharging of the battery when it is powering something from a distance. I powered the display module from a
a load, or overcharging when it is being charged. You can also set small powerbank, allowing me to walk around the house with the
a maximum positive current (from the power source to the load) module. You have to be careful with the distance (10 m max.) since
and a maximum negative current (from the charger to the battery) the range drops quickly if there are a few walls between the display
for switching the relay. With this combination you can easily keep and measurement modules. However, the display module includes
track of how much power a connected circuit uses, or how much a signal strength indicator that makes it easy to monitor this.
energy was stored in a battery during charging, without having to
resort to a calculator. The battery icon can also be hidden if you do Conclusion
not need it in a particular application. This set of measurement and display modules is very handy and
affordable for measuring voltage and current in all sorts of circuits.
Practical experience Thanks to the large current range (30 A), it is ideally suited to situa-
The JOY-iT user guide included with the device provides enough tions with high current levels. The ability to use the wireless display
information to get you started, but to learn how to use all the module in one location, while measuring the data somewhere
features properly we recommend that you try each functionality else, is a valuable extra feature that you would scarcely expect at
in the list of menu items. this price. This combination of capabilities is certainly worth the
price of around €40/£35/$45.
The measured voltage and current are shown on the display with 200571-02
two digits before the decimal point and two digits after (Figure 4
and 5). According to the user guide, the accuracy is ±2% for voltage
and ±5% for current. This turns out to be reasonably correct in a
comparison test with an accurate multimeter. Unfortunately the
display module shows a small voltage even without an input voltage
applied, which is a pity. Although it is within the 2% accuracy speci- RELATED PRODUCTS
fied, it does seem a little strange.
> JOY-iT VAX-1030 Wireless Multimeter
The connector PCB in the measurement module has a jumper with www.elektor.com/joy-it-vax-1030-wireless-multifunction-meter
positions marked 2W and 3W. This jumper is not mentioned in the
The measurement principle, the calibration in software and the hardware of this new LCR
meter was discussed in the first part of this article series. In this second and final part, we will
cover the user interface, the calibration, and firmware programming of the AU2019.
In Part 1 of this series, we saw how the AU2019 Operating the LCR meter Stand-alone mode
works, how it measures impedances, the The AU2019 can be used as a stand-alone If the device is fitted with the display exten-
calibration and compensation principles used measurement device, using its LCD, the sion, it can operate independently, without
and the hardware needed. Now it is time to rotary encoder and buttons, but it can also a computer. In this mode, it starts automati-
have a look at this LCR meter from a user’s be operated by a computer via a USB-link. cally when using an external 5 V USB power
point of view. supply. However, if it is being powered from
Table 1.
50 60 Hz
100 120 150 200 250 300 400 500 600 700 800 900 Hz
1.0 1.2 1.5 2.0 2.5 3.0 4.0 5.0 6.0 7.0 8.0 9.0 kHz
10 12 15 20 25 30 40 50 60 70 80 90 kHz
100 120 150 200 250 300 400 500 600 700 800 900 kHz
1.0 1.2 1.5 2.0 MHz
Table 2.
Figure 3: Controlling the LCR meter via the AU2019 app. 5 +7.5V 7.30V < Ux < 7.60V
Resistor (Figure 4)
In most cases, resistors can be measured
with a good multimeter! On the other hand, a b
it may be interesting to know the parasitic
series inductance of a low ohm resistor at
high frequencies, or the parasitic capacitance Figure 4a: Measuring low-ohm resistor at high Figure 4b: Measuring high-ohm resistor at low
of high value resistor. frequency. frequency.
a b c
Figure 5a: Measuring a small capacitor at higher Figure 5b: Measuring a large capacitor at low Figure 5c: Measuring a large capacitor at low
frequency. frequency. frequency and 5 VDC bias.
Figure 6a: Measuring an inductor with bias Figure 6b: Measuring an inductor at higher Figure 6c: Measuring an inductor without bias
current. frequency. current.
LOADING THE FIRMWARE Figure 7a: Programming settings in Silicon Labs’s MCU Production Programmer.
FOR THE FIRST TIME
Connect the USB Debug Adapter cable to J15 on the
board and the PC and set SW1 to ON. Run the MCU
Production Programmer [3]:
> Go to Program Menu / Configure Programming Information... and copy all
settings as in the screenshot below, then Accept Settings (you can save
these settings by Save Settings...) (Figure7a/b)
> Click on Program Device to launch the operation.
> After programming is finished, Device Programmed and Verified message
appears in the Status Log window
> Then the display texts (language file) must be uploaded using the
instructions in the Operating instructions document §4.2.5.
WEB LINKS
[1] Documentation and Software Download: www.elektormagazine.com/190311-01
[2] New LCR Meter Project Page on Labs: www.elektormagazine.com/labs/remake-lcr-meter
[3] Silicon Labs Production Programmer Download: www.silabs.com/documents/login/software/MCUProductionProgrammer.zip
Questions or Comments?
Do you have questions or comments
about his article? Email the author
at jjacques.aubry@free.fr.
RELATED PROJECTS
> Elektor “Kickstarter” Project:
Kit including Main Board + Display Extension Board + all parts
www.elektor.com/lcr
Error Analysis
Tips on Voltage Regular Circuits, PCB Design, and More
A Case for Voltage Regulator Circuits LEDs inside clear tubing. I calculated the voltage at 13VDC based
on measurements while the boat motor was operating. Then
Have you ever spent hours on an electronics project only to have it I made the mistake of starting the engine without the battery
all go “poof” due to a simple mistake? Scott Coppersmith — a Senior connected and every LED burned out in unison when the alter-
Research Engineer at the University of Notre Dame in South Bend, nator output jumped to 21 VDC. Hours and hours of work — poof.
Indiana, USA — has been there. He recently shared his experience Automotive and marine power systems can vary wildly from 8
and offered a tip. volts to 18 volts or more depending on charge state and load on
the battery. It’s best to have your own voltage regulator circuits
“I designed a lighting solution for my boat once by stringing for these applications.” — Scott Coppersmith
All Components Are Suspect faulty but brand new components. These included transistors
with their complimentary device in the package or their marking
Looking for tips about printed circuit board (PCB) design? Chris Clapham switched (not sure which) — that is, a PNP in a case with an NPN
is an Auckland, New Zealand-based hardware engineer with 30-plus part number, efficiency diodes that measured nearly identical to a
years of experience working with PCBs. He offers some great advice: good one but did not work properly leaving the power supply to run
always check your components. Even new components can be faulty. very hot. We even had a diode which had the anode and cathode
swapped. The device the TV manufacture had used (they got them
“Never remove brand new components from the suspect list! While cheap) had the cathode connected to the metal tab (TO-220 type
working for a TV PCB reconditioning company 30-plus years ago case from memory) and that was connecting to the heatsink,
— where we not only repaired faulty PCBs, but they were recondi- which was grounded (no insulator) but the new part (correctly
tioned, electrolytics replaced, dry joints resoldered, etc., and any made) had the anode connected to the tab, so it shorted when
stressed looking components replaced — we came across a few fitted until you figured out that it needed a mica washer to make it
Advertisement
Authors Wanted
Covid-19 has had a considerable impact on all our
lives and the way we spend our time.
elektor.com/authors--wanted
elektor.com/authors
The Open Hardware Observatory is an initiative that aims to make open hardware more
accessible. It provides a search engine to help you find open hardware projects published
anywhere on the web. And it is currently developing a community-based platform for
reviewing open source hardware documentation based on DIN SPEC 3105. The Observatory
is being developed by a group of people from Open Source Ecology Germany e.V. and TU
Berlin. Lukas Schattenhofer — together with Consuelo Alberca Susano, Mehrdad Mansouri,
and Nils Weiher — is currently working on the community around the Observatory.
Schattenhofer explains how it works and invites Elektor readers to join the community.
Open-source hardware (OSH) is hardware whose design is made publicly under copyright law too. Not all makers are aware they have to explicitly
available so that anyone can study, modify, distribute, make and sell assign an open license to enable downstream users to legally re-use
the design or hardware based on that design [1]. To understand the the code or distribute the documentation.
benefits of open hardware, we would have to change our perspective
on technology, says Lukas Schattenhofer. “For most people, technology The second criterion concerns the documentation. Schattenhofer:
is currently something you consume rather than build and maintain. If a “Documentation is important. OSH is about enabling people to study,
component of their phone breaks, they buy a new one instead of fixing modify and make the hardware. And for that you need the designs.
it. Today, most technology is closed. That means that the information You can’t download the source code as you do with software. With
you need to make repairs isn’t accessible. But if all the documentation hardware, the documentation is the source.”
is available, you wouldn’t need to buy a new phone every two years.
You would be able to repair it and even build it. Also, it would change Therefore, documentation needs to be in compliance with a minimal
the way products are designed. They would become more modular so set of requirements. An enthusiastic maker who’s uploaded a Youtube
you can swap out parts and combine products with each other.” video of their DIY drip irrigation system probably wants to share it. But
if the video lacks the information needed to reproduce the project, it
“Documentation is the source” isn’t really open source.
But even though there is a thriving open hardware community, OSH
is still much less known than its counterpart open-source software. Documentation assessment platform
The Open Hardware Observatory (OHO) aims to make OSH more Schattenhofer and the team are currently working on the assess-
visible by providing an online repository of open projects [2]. To ment platform. The review process works as follows. An applicant
do so, OHO has created a search engine that crawls the web for uploads a project. Three reviewers assess the documentation. They
projects. These are listed with photos and a short description. But can add comments to point out which parts are missing or should be
not all the projects in the repository are truly open. That is where improved. When the documentation meets all the requirements, the
the second branch of OHO comes in — the assessment platform. project receives an attestation.
It helps makers present their project in such a way that it complies
with the standards for OSH. The requirements for the documentation are laid down in DIN SPEC
3105. This is a Publicly Available Specification submitted to DIN, the
There are two main criteria for a project to be open. First, there are German standards body. It specifies concrete measurable criteria for
the licenses. Code or firmware is automatically copyrighted. If a maker OSH compliant documentation. The specification is itself the result
includes software in their project, they must actively assign it an open of a collaborative process of the OSH community. And in accordance
license like the Gnu General Public License or the MIT license [3]. with open source principles, anyone can contribute to the further
Product documentation, especially when it is extensive, often falls development of DIN SPEC 3105 via the Gitlab page [4].
improving the user experience. Schattenhofer and the team are inviting Note: OHO was founded as a collaboration between the non-profit
Elektor readers to join the OHO community. You can join by uploading association Open Source Ecology Germany e.V. (OSEG) and the
your project for review. Or you can apply your technical knowledge as a French-German research project OPEN! Methods and tools for commu-
reviewer. But, Schattenhofer warns, you should be ready to deal with a nity-based product development [6].
website that is not entirely ready yet. So there’s a third role you can take 200560-01
on in the OHO project. You can get involved as a tester of the platform
and help to create a better user interface and workflow.
Schattenhofer: “At the moment, not many people know DIN SPEC 3105
and the community-based assessment platform yet. But we want to
build an active community around the Open Hardware Observatory to
Questions or Comments?
advance mainstream adoption of open source hardware. People who
Do you have questions or comments regarding this article?
join the OHO community now, can really be part of the development
Then get in touch with the Elektor editorial team at
process. If you get involved now, you can bring in your own ideas. If
editor@elektor.com.
you are interested in joining OHO, you can contact us at info@oho.wiki.”
Contributors
Text: Tessel Renzenbrink Editor: Stuart Cording Layout: Giel Dols
WEB LINKS
[1] This widely used definition was established by the Open Source Hardware Association (no relation to OHO).
[2] Open Hardware Observatory: https://en.oho.wiki/wiki/Open_Hardware
[3] List of Open Licenses: https://opensource.org/licenses
[4] DIN SPEC: https://gitlab.com/OSEGermany/OHS/
[5] Open Source Hardware Association Certification: https://certification.oshwa.org/
[6] Founding Partners: https://en.oho.wiki/wiki/Founding_partners#TU_Berlin_.2F_Research_project_OPEN.21
Java on the
Raspberry Pi
An Interview with Frank Delporte
By C. J. Abate (Elektor)
You can run Java on the Raspberry Pi. In this interview, Elektor author
Frank Delporte covers the benefits of Java, his Raspberry Pi-based projects,
and much more.
Want to run Java on the Raspberry Pi? experience which was really worth all the
Belgium-based Frank Delporte can help. His hard work.
new book, Getting Started with Java on the
Raspberry Pi [1], is an excellent resource for Abate: Speaking of your writing and editing
both professional programmers and makers work, we featured your home workspace
interested in experimenting and learning at [3] on the Elektor magazine website in May
their own pace. In this interview, Delporte 2020. Are you still working from home due
talks about the benefits of combining Java to the COVID-19 situation?
and Raspberry Pi, as well as his experiences
as a programmer. Delporte: The situation is more-or-less
back to normal now. I still work at home
Programming, designing, but not really for Covid. At work, we can
and writing keep enough distance, but from time to
time, it’s still better to work home so you
Abate: Congratulations on publishing can focus on a specific task.
the book, Getting Started with Java on the
Raspberry Pi (Elektor 2020). I will ask more Abate: You have an interesting background,
about the book in a bit. But first: are you which includes work as a software devel-
happy to have all the writing and editing oper, technical lead, author, and video
behind you now? Or do you enjoy that sort editor. Tell us more about yourself.
of work?
Delporte: I’ve always been interested in
Delporte: I really love to write as you can technology and how things work. I was
see on my blog [2]. But I have to admit a full the kind of kid that opened every coffee
book was a lot of work. It requires not only machine, radio or whatever device which
the writing itself, but also collecting all the was broken. I wasn’t able to fix them all,
required information, research, setting up but I learned something new every time!
experiments, drawing eletronic schemes, As a teenager I had a radio show on a local
doing interviews, re-reading, etc. But the station and did some DJing which gave me
feeling of holding your first finished printed the possibility to experiment more with
paper book (Figure 1) is a once-in-a-lifetime electronics.
That’s why I decided to study at a (techni- started taking off, I switched to web devel- Abate: At which point did you realize, “Hey,
cal) film school were we learned how film, opment as my customers wanted to share I’m a good instructor/teacher, and I think
radio and television are produced, how the same information on websites with a I can help others interested in Java”? Or,
you calibrate cameras and connect all the content management system. And with did a friend or colleague point you in that
devices and recordings together. After I that knowledge, I grew into Java develop- direction?
graduated, video production changed a lot ment and technical lead doing product
when computer editing got introduced, and development using that technology. Delporte: I like to explain things and
that’s how I got into programming again strongly believe in “learn by teaching.”
when clients wanted their company video Teaching code That’s what I do at CoderDojo with children,
on CD-ROM and Internet. but also with my blog and at work. To fully
Abate: When did you start organizing understand a topic, you must be able to
Abate: In your bio, you mention the CoderDojo sessions? And what sort of explain it — or vice versa. The articles I
Commodore 64. Do you remember any of courses do you teach? write for my blog are always the result of
your early experiences with it? something I want to try out but don’t really
Delporte: In every company I’ve worked, it know how to do it (yet). During the process
Delporte: I only had one game on my has been a challenge to find good techni- of figuring it out, I write down the steps I’ve
C64, because I really got more interested cal colleagues. Engineering (and definitely taken and what worked and didn’t work.
in programming. Thanks to Elektor, I IT) is still a too male environment. To me, That’s how I learn new stuff and can share
found a book (must be around 1987) with engineering is magic. With a few lines of that knowledge with others.
an electronics board with eight relays you code or a few electronic components, you
could control with the C64 and Basic. I can build “stuff.” I wondered why kids — who A focus on Java
used it to control my Lego train and used love to build and experiment — suddenly
magnetic switches to detect the position of stop doing this and don’t choose a study Abate: Tell us about your history with Java.
that train through the joystick ports. That where they can continue “making things.” Did you first learn it out of curiosity? Or was
was the first time I managed to combine it for a class? Or for work?
software and hardware. Nowadays, such a CoderDojo [4] is a free club where volun-
project would be a lot easier (and cheaper) teers help children from seven to 18 to Delporte: When I started developing multi-
with Arduino or a Raspberry Pi and the experiment with “digital stuff.” We use media applications, I had to learn Action-
many great extension boards. Scratch (block based programming) for Script (and even Lingo before that). Later, I
programming, build worlds in Minecraft changed to C# and SQL for the web applica-
Abate: What were your career goals in 1994 with JavaScript, control electronics with tions. As you may now know already, I learn
when you left NARAFI Nationaal Radio en Arduino, build robots with Lego, and much by experimenting. But also from reading
Filmtechnisch Instituut in Belgium? more. In 2013, I started such a club in Ieper books and short (on-line) courses. When
and Roeselare and still lead the one in Ieper I started at Televic Rail in 2010, I joined a
Delporte: My first job was video editing — except now during Corona times, as it team which was already using Java. Switch-
at a local TV station, and after a few years, is difficult to organize such informal clubs ing from C# to Java was very easy. After all
I started doing the same as a freelancer. I when you have to keep a safe distance and these years of programming, I have to say
never had a clear career goal but rolled from can not gather around a PC with different I learn the most from colleagues! Sharing
job to job and learned new things along people. Thanks to CoderDojo and other your work with others in presentations,
the way. That’s how I transformed myself STEM (Science, Technology, Engineering improving the code with pull requests,
from video editor to multimedia devel- and Mathematics) initiatives, we see a accepting comments as how you can do
oper building company presentations on slow increase in the number of engineer things better are all the best ways to learn
DVD and CD-ROM. And when the Internet students — boys and girls! from others.
Since I started experimenting with Java experience with Arduino and Raspberry I also joined the Pi4J-team. Pi4J is a frame-
on Raspberry Pi, I got involved in some Pi. They brought there kits to the club, and work and library to combine Java applica-
open-source projects and discussions, and I was really amazed of the power of these tions with the full power of the GPIOs of
that’s a complete new world to me, where inexpensive boards and what you can the Raspberry Pi. This project was started
I meet a lot of very bright people who are achieve with them combined with small by Robert Savage, and he was looking for
also willing to share their knowledge and electronic components. extra team members to bring this project to
experience. Still every day I’m amazed by a new generation which fully supports Java
the stuff you can learn from these projects I was blogging already for some time, but 11+ and the Raspberry Pi 4 with Java modules
and people. You don’t have to contribute my first “public” Raspberry Pi-project was and an easily extendable architecture. I’m
code, but you can also join such a project indeed this Pong game that we used on really excited about the second version of this
by reviewing pull requests, helping to test some activities of the school of my son. framework, which we hope to release soon.
or document the code. I used Python for the user interface; but
I have to be honest, I didn’t like to code Abate: Let’s return to the book, Getting
Abate: Are you anti-Python or anti-C? I it very much. For that kind of applica- Started with Java on the Raspberry Pi. Why
assume you aren’t, but I have to ask. tion, I really prefer JavaFX for which there did you write it?
is even a very nice gaming framework:
Delporte: Definitely not! I hate haters. FXGL [6]. Delporte: When starting the drum booth
There are no bad programming languages! project, I had to find out how to use Java on
I once read a quote which says, “The best Abate: Do you have any RPi-based designs the Raspberry Pi, how to install the right
tool for the job is the one you know the or applications running at home or in your version of JavaFX, how to control the GPIO
best.” In my case, that’s Java and JavaFX if workspace? and an Arduino, etc. That’s when I wrote my
I want to make an application with a nice first article [9], which was published in MagPi
user interface. But in my book, I also used Delporte: I started with Java on the (July 2019, Dutch [10] and French [11] edition).
Python to control a LED number display Raspberry Pi to build a drum booth control-
and an Arduino with LED strips. ler [7] for my son. It’s a touch-screen user Elektor contacted me and asked if this
interface to control multiple lights with a could be the subject of a book. As I couldn’t
For each project (Figure 2), you must make relay-board and LED strips controlled by find a recent one on this topic and Java
a decision what the best tool, programming Arduino (Figure 3). had some major changes in the last years,
language or framework is. And once you’ve this question really triggered me and the
decided, go for it! Maybe you’ll realize later This way I learned to use serial communi- next day I started writing. It took me more
you didn’t make the best choice, but at least cation between the two boards and I²C to than six months and a lot of evening and
you will have learned new things. control the relays. In my book, I extended nights, but I really had fun while writing
this further and used a Mosquitto queue to and experimenting. And, of course, I hope
Working with Java on the exchange messages between more boards it’s as much fun to read the book and try out
Raspberry Pi and PCs. the projects that I included.
Abate: You have been blogging about technol- Abate: What else are you working on these Abate: Do you have any advice for engineers
ogy since 2007. It looks like your first post days? New projects, programs, or books? or makers who are thinking about using Java
about Rapsberry Pi was “Pong on a Raspberry for their Raspberry Pi-based designs?
Pi” [5] (December 2017). Can you tell us about Delporte: I’m further experimenting with
your first experiences and projects with RPi? Java on the Raspberry Pi, of course. I wrote Delporte: Try it, really! Java is still one of
When did you get started with it? some more blog posts on this subject and also the top programming languages world-
experimented with other Java technologies wide. Whether you are an experienced
Delporte: When I started with CoderDojo, (Quarkus [8], Spring, GraalVM) and 64-bit Java developer or starting from scratch,
there were some coaches who already had operating systems on the board. there is a lot to learn and experiment when
you combine Java with a Raspberry Pi and Abate: Is there a programming language ger information to screens on whole sets of
electronic components. that you don’t know that you plan to learn? trains. Solving this technical challenge and
Any hardware you’re thinking of trying out? finally walking through a driving train with
The examples in my book use very cheap 100 screens showing the departing trains at
parts like LEDs, buttons, LCD, LED number Delporte: Java is not only a programming the next station with real-time delays and
display, etc., so you may already have these language, but also a virtual machine which platform changes is very satisfying.
available, or find them in any starter kit. All runs the Java code. On this same VM, you The flow needed to bring all this data
the book examples can be used to combine can also run Scala, Kotlin and many other through unreliable wireless connections
them to the project of your dreams. The languages. So still a lot to explore within (GSM signals aren’t really designed to handle
drumbooth controller I made for my son is this world. For the Pi4J project, I want to fast driving vehicles) is a real masterpiece of
a combination of multiple of those examples extend the example code and documenta- which I’m very proud we could realize with
(Figure 4). tion website, so I will need to set up multiple a small team. But I’m equally impressed by
small hardware examples and learn a lot of the children at CoderDojo who manage to
Abate: What has the feedback been so far? new stuff myself. make their first Flappy Bird game in Scratch
or blink a LED with Arduino!
Delporte: Although Python was the initial Programming success 200503-01
language to be used on the Raspberry
Pi (yes, that’s where the Pi comes from) Abate: Let’s wrap up with your biggest
and some still believe it’s the only right engineering- or programming-related
choice, I got a lot of positive feedback success. Is there a specific project (software
and questions on this topic. I even got the or hardware) that stands out? What was diffi-
chance to write a post for the Oracle Java cult about that project? What did you learn? Related Product
Magazine [12], which got a lot of readers
and shares! There is a clear interest in Delporte: In my job at Televic, we use > F. Delporte, Getting Started with
this topic, and the future new generation a combination of Java and embedded Java on the Raspberry Pi
www.elektor.com/19292
of Pi4J will make it even easier to build programming to connect multiple servers
powerful applications. and data sources to bring real-time passen-
WEB LINKS
[1] Getting Started with Java on the Raspberry Pi: www.elektor.com/getting-started-with-java-on-the-raspberry-pi
[2] WebTechie Blog: http://webtechie.be/
[3] “A Software Developer’s Space for DIY Projects and Writing”:
www.elektormagazine.com/news/electronics-workspace-software-developers-space
[4] CoderDojo: http://coderdojo.com/
[5] “Pong on a Raspberry Pi”: http://webtechie.be/post/2017-12-20-pong-on-a-raspberry-pi/
[6] “Getting Started with FXGL Game Development”: http://webtechie.be/post/2020-05-07-getting-started-with-fxgl/
[7] “Drumbooth Controller with Raspberry Pi and JavaFX”:
http://webtechie.be/post/2020-03-30-drumbooth-controller-with-java-javafx-raspberrypi-arduino/
[8] Quarkus: http://webtechie.be/post/2020-07-28-spring-versus-quarkus-rest-h2-db-on-raspberry-pi/
[9] WebTechie Articles: http://webtechie.be/articles/
[10] MagPi (Dutch): www.magpi.nl/
[11] MagPi (French): www.magpi.fr/
[12] “Getting Started with JavaFX on Raspberry Pi”: http://blogs.oracle.com/javamagazine/getting-started-with-javafx-on-raspberry-pi
Data Analysis
and Artificial
Intelligence in
Python
Interpreting real data with NumPy,
pandas and scikit-learn
The analysis and interpretion of data the entire production line, or make use of contextual information
that originates from our surroundings that indicates the age and type of each machine. This set of data,
or dataset, can be used for different purposes. This could include
and environment is a topic of increasing predictive maintenance, allowing us to evaluate and predict the
interest. Such data is now an established occurrence of abnormal situations, plan orders for replacement
part of our everyday lives, ranging from that parts, or undertake repairs before failures occur, all of which result
in cost savings and increased productivity. In addition, the knowl-
collected about our climate to data acquired edge of the data’s history allows us to correlate the data measured
during smart manufacturing processes. by each sensor, highlighting possible cause/effect relationships.
The quantity of data allows us, in theory, to As an example, if a sudden increase in temperature and humidity
of the room was followed by a decrease in the number of pieces
characterize any phenomenon. However, manufactured, it may be necessary to make changes that maintain
dealing with it requires the mastery of many constant climatic conditions using air conditioning.
skills, both theoretical and practical. Here we
The implementation of such a system is certainly not within every-
examine some of these techniques and make one’s reach. However, it is simplified by the tools made available
use of Python for the analysis of this real- by the open source community. All that is required is a PC (or,
world data. alternatively, our trusty Raspberry Pi can be used, if the amount
of data to be processed is not huge), a knowledge of Python (which
you can deepen by following a tutorial like this [2]) and, of course,
By Angelo Cardellicchio (Italy) some knowledge of the ’tools of the trade’. OK — let’s get started
and discover them together!
Terms such as big data and artificial intelligence have become a
permanent entry in our everyday language. This is primarily due The tools of the trade
to two factors. This first is the increasing and pervasive diffusion of Needless to say, we must be able to create programs written in
data acquisition systems that has allowed the creation of virtually Python. To do so, we will have to install the interpreter. This can be
endless knowledge repositories. The second is the continued growth found on the official Python website [3]. In the rest of this article
in computational capability, due to the widespread use of GPGPUs we will assume that Python has already been installed and added
(general-purpose graphics processing units) [1], which has made to the system environment variables.
it possible to tackle computational challenges whose resolution
was once considered essentially impossible. The virtual environment
Once the Python setup is complete, it is time to set up a virtual
Let’s start with the description of an application scenario that environment. This is implemented as a sort of ’container’ that is
will accompany us through this article. Let’s imagine having to separate from the rest of our system and into which the libraries
monitor an entire production chain (the precise product does used are installed. The reason for using a virtual environment for
not play a role here). We have the ability to acquire data from a the global installation of libraries relates to the rapid evolution of
wide range of sources. For example, we can place sensors along the Python world. Very often, substantial differences arise even
we can think of a dataset as an Excel spreadsheet. The rows provide sentative of the reading of a single sensor at a given instance in
the samples, that is the individual observations of the phenome- time. The dataset also contains labels that distinguish failures and
non, while the columns provide the features, that is the values anomalies from the proper functioning of the system.
that characterize each of the aspects of the process. Returning to
the example of smart manufacturing, each row will represent the Once the dataset is downloaded, we install the libraries mentioned
conditions of the production chain at a given moment while each above. From the command line, enter:
column will indicate the reading of a given sensor. $ pip install numpy pandas scikit-learn matplotlib
seaborn jupyter numpy pandas install
When we talked about Scikit-Learn, we briefly mentioned
the concept of label or class. The presence or absence of labels Once the libraries are installed we can set up a simple pipeline
allows you to distinguish between supervised and unsupervised for data analysis.
algorithms. The difference is, at least in principle, quite simple:
supervised algorithms require a priori knowledge of the class of each The first notebook
sample in the example dataset, while the unsupervised algorithms do The first step is to create a new notebook. From the command line
not. In practical terms, to use a supervised algorithm it is required we launch Jupyter using the following instruction:
that a domain expert establishes the class of belonging for each $ jupyter-notebook
sample. In the case of a smart manufacturing process, an ’expert’
could determine if a set of readings, from a specific moment of time, A screen similar to the one shown in Figure 1 will open. We create
represent an abnormal situation or not. Thus the single sample a notebook by selecting New > Python 3. A new tab will open in our
can be associated with one of these two possible classes (abnor- browser with the newly created notebook. Let’s take a moment
mal/normal). This is not necessary for unsupervised algorithms. to familiarize ourselves with the interface, shown in Figure 2,
which resembles (very vaguely) an interactive command line, a
Futhermore, a distinction must be made between processes with top menu, and several options.
independent and identically distributed data (IID) and with data in
a chronological order. The difference is related to the nature of the The first thing that jumps out is the cell, one part of the view we
phenomenon under observation. Samples of an IID process are can now see. The execution of single cells is initiated by the Run
independent of each other, while in a time series each sample button and is independent from that of the other cells (we must
depends on a linear or non-linear combination of the values that keep in mind that the concept of scope of variables remains valid).
the process output at previous points in time.
The three buttons immediately to the right of the Run button
Let’s get started! allow you to stop, reboot and reset the kernel, i.e. the instance
With the necessary theoretical and practical terms covered, we that Jupyter associates to our notebook. Restarting the instance
move on to using a suitable dataset for our example case. The may be necessary to reset the local and global variables associated
dataset used is SECOM, an acronym that stands for SEmiCOnductor with the script, which is especially useful when you are experi-
Manufacturing, that contains the values read by a set of sensors menting with new methods and libraries.
during the monitoring of a semiconductor manufacturing process.
In the dataset, which can be downloaded from different sources Another useful option is the one that allows you to select the cell
(such as Kaggle [5]) there are 590 variables, each of which is repre- type, choosing between Code (i.e. Python code), Markdown (useful
for inserting comments and descriptions in the format used, for Visualizing the first lines of the dataframe can be useful to have a
example, by GitHub READMEs), Raw NBContent (plain text) and first overview of the data to analyze. In this case we immediately
Heading (offering a shortcut to insert titles). notice the presence of some values equal to ‘?’ that presumably
represent null values. Moreover, it is evident that the range of the
Importing and displaying data values vary greatly, a factor that we will have to keep in mind later
Once we are familiar with the interface we can move on to imple- on. We can also use the describe() function to get a quick overview
ment our script. Here we import the libraries and modules that of the statistical characteristics of each variable (Figure 4).
we will use: data.describe()
import numpy as np Statistical analysis can, in general, highlight conditions with a lack
import pandas as pd of normalcy (i.e., data distributed according to a non-parametric
import matplotlib.pyplot as plt distribution), or the presence of anomalies. To offer an example,
%matplotlib inline we note that the standard deviation (std) associated with the
import seaborn as sns variables a116 and a118 is, proportionally, quite high, so we expect
from ipywidgets import interact a high significance of these variables in their analysis. On the other
from sklearn.ensemble import RandomForestClassifier hand, variables such as a114 have a low std, so they are expected to
from sklearn.impute import SimpleImputer be discarded as they are not very explanatory with respect to the
from sklearn.model_selection import train_test_split process being analyzed.
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, Once the loading and display of the dataframe is complete, we
accuracy_score can move on to a fundamental part of the pipeline: preprocessing.
from sklearn.utils import resample
Preprocessing data
It is worth highlighting the instruction %matplotlib inline that As a first step we display the number of samples associated with
allows us to display the graphs produced by Matplotlib correctly. each class. To do so, we will use the value_counts() function on
the classvalue column as it contains the labels associated with
Next, the data of the file containing the SECOM dataset is imported each sample.
using the Pandas read_csv function. Note that, in this example, data[’classvalue’]. value_counts()
the relative path to the file is hardcoded for the sake of simplicity.
However, it would be advisable to use the Python os package to We see that there are 1463 samples collected in the normal operat-
allow our program to determine this path itself when required. ing situation (class -1) and 104 in the failure situation (class 1). The
data = pd.read_csv(’data/secom.csv’) dataset is therefore strongly imbalanced and it would be appropriate
to undertake steps to make the distribution of samples between the
The previous instruction reads in the data contained in the secom. different classes more ‘uniform’. This relates back to the intrinsic
csv file, organizing it in a dataframe named data. We can display functionality of machine learning algorithms that learn on the basis
the first five lines of the dataframe through the head() instruction, of the data available to them. In this specific case, the algorithm will
as shown in Figure 3. learn to characterize a situation of standard behavior successfully,
data.head() but will have ’uncertainties’ in characterizing abnormal situations.
The unbalance is even more evident when looking at the scatterplot column into numeric values. By combining them we generate unique
(shown in Figure 5): data and we will also remove the values that cannot be handled by
sns.scatterplot(data.index, data[’classvalue’], alpha=0.2) Numpy and Scikit-Learn:
plt.show() data.apply(pd.to_numeric)
With this imbalance in mind (we’ll come back to it later), we proceed We now need to evaluate which features among those contained in
to ‘separate’ the labels from the data: the dataset are actually useful. We typically use techniques (of higher
labels = data[’classvalue’] or lower complexity) of feature selection to reduce redundancies and
data.drop(’classvalue’, axis=1, inplace=True) the size of the problem to be treated, delivering obvious benefits in
terms of processing time and performance of the algorithm. In our
Note the use of the axis parameter in the drop function that allows case, we rely on a less complex technique that involves the elimina-
us to specify that the function must operte on the columns of the tion of features of low variance (and therefore, as mentioned above,
dataframe (by default, Pandas functions operate on the rows). of low significance). We create, therefore, an interactive widget that
allows us to visualize, in the form of a histogram, the distribution
Another aspect that can be extrapolated from the dataset analysis is of data for each feature:
that, in this specific version of SECOM data, many columns contain @interact(col=(0, len(df.columns) - 1)
data of different types (i.e. both strings and numbers). As a result, def show_hist(col=1):
Pandas is unable to uniquely determine the type of data with which data[’a’ + str(col)]. value_counts().hist(grid=False,
each feature is represented and defers the definition of this to the figsize=(8, 6))
user. Therefore, to bring all data into numerical format, it is neces-
sary to use three functions offered by Pandas. Interactivity is ensured by the decorator @interact, whose reference
value (i.e. col) varies between 0 and the number of features present
The first function we will use is replace(), with which we can replace in the dataset. Exploring the displayed data through the widget, we
all question marks with the constant value numpy.nan, the place- will determine how many features assume a single value, meaning
holder used to handle null values in Numpy arrays. they can be simply overlooked in the analysis. We can then decide
data = data.replace(’?’, np.nan, regex=False) to eliminate them as follows:
single_val_cols = data.columns[len(data)/data.nunique()
The first parameter of the function is the value to replace, the second < 2]
is the value to use for the replacement, and the third is a flag indicat- secom = data.drop(single_val_cols, axis=1)
ing whether or not the first parameter represents a regular expres-
sion. We could also use an alternative syntax using the inplace Of course, there are more relevant and refined feature selection
parameter set to True, as follows: techniques using, for example, statistical parameters. For a complete
data.replace(’?’, np.nan, regex=False, inplace=True) overview, the Scikit-Learn documentation can be consulted [6].
The second and third functions that we can use to solve the problems The last step is to deal with the null values (which we replaced previ-
highlighted above are the apply() and to_numeric() functions ously with np.nan). We inspect the dataset to see how many there
respectively. The first allows you to apply a certain function to all are; to do so, we use a heatmap, as shown in Figure 6, where the
columns (or rows) of a dataframe, while the second converts a single white points represent the null values.
WEB LINKS
[1] MATLAB GPU computing support: https://uk.mathworks.com/solutions/gpu-computing.html
[2] Beginners guides for Python programming: https://wiki.python.org/moin/BeginnersGuide/Programmers
[3] Python: www.python.org/
[4] Best practices for optimisation in MATLAB:
https://uk.mathworks.com/videos/best-practices-for-optimisation-in-matlab-96756.html
[5] UCI SECOM dataset: www.kaggle.com/paresh2047/uci-semcom/kernels
[6] Scikit-Learn user guide: https://scikit-learn.org/stable/user_guide.html
[7] Overfitting vs. underfitting: a complete example:
https://towardsdatascience.com/overfitting-vs-underfitting-a-complete-example-d05dd7e19765
[8] Understanding random forest: https://towardsdatascience.com/understanding-random-forest-58381e0602d2
[9] Understanding confusion matrix: https://towardsdatascience.com/understanding-confusion-matrix-a9ad42dcfd62
[10] GitLab repository for this article: https://gitlab.com/eos-acard/machine-learning-in-python
Project 2.0
Corrections, Updates and Readers’ Letters
By Ralf Schmiedel (Elektor) and Jens Nickell (Elektor)
Questions or Comments?
Do you have questions or comments? Then get in touch with
Elektor by email at editor@elektor.com.
190381-E-03
1
Professional field
Working from ... Top 3
1) Electronics development
92% of members 2) Computing
have their own 3) Microcontrollers 2
HOMELABS
Coding skills
1 two_or_more = 64
2 four_or_more = 20
3 print(two_or_more + ″ % kno
ws two or more programming
languages.″)
4 print(four_or_more + ″ % kno
ws four or more programming
languages.″)
Community us
Insights in
> 43,200 Facebook followers
> 13,600 Twitter followers
> 2,000 LinkedIn followers
>1,800 Instagram followers
Getting to Know
the Parallax Propeller 2 (Part 1)
An Introduction
When Parallax introduced its first Propeller chip in 2006, it was and 512 × 32 Bit Lookup RAM per core. Besides core count and
something different than what we had seen before. In recent RAM, the chip includes a whole set of interesting peripherals and
months, while working on the Propeller 2, Parallax has asked features that include:
users and engineers to give feedback, as the first appearance of
the chip was not in form of silicon but was given as bitstream for an > CORDIC solver with scale-factor correction
Altera DE10-Nano FPGA board. Over the time Parallax collected the > 16 semaphore bits with Atomic read-modify write
feedback and went on to get the design for the Propeller 2 in silicon. > 64 bit free running counter
Fortunately, the company wrote about the process in the Propeller > USB 2.0 FS host and slave interface
forum so that the community can learn about the chip manufac- > Smart I/O pins (For more details, refer to the “Smart Pin
turing process. As I write this, Revision C silicon is approved for Functions” textbox.)
production. Let’s take a look at the Propeller 2 and its features.
Parallax was kind enough to send us an evaluation kit (Figure 1) with
The Propeller 2 a Revision C engineering sample on it, so that we could have a first
The chip is officially rated for 180 MHz clock speed, resulting in look at and start playing. So I will use this article series to give you
90 MIPS per core, and every instruction takes at least two clock some insight into the chip, its peripherals, sample code, and more.
cycles. Overclocking the Propeller 2 is possible and speeds beyond
300 MHz can be reached, resulting in 150 MIPS per core. When A word of warning: as I write this, the chip is officially not released,
it comes to CPU cores, your microcontroller has usually one, or so you should expect that we will hit some rough spots when it
sometimes two. The Propeller 2 has eight independent cores, called comes to software that might still be under construction. We were
cogs, which provide a lot of computation power. All cogs share provided with not only the evaluation board, but also a stack of
512 KB RAM on this model, and additional 512 × 32 Bit Registers add-ons to test and play with (see Figure 2).
Where have the peripherals gone? the individual peripherals and their special features will be quiet
Wondering where the SPI, I2C and UART modules are? Those can long and boring at the beginning, we are going to introduce them
be formed by using the smart pins and some code inside the cogs. while we move along with the Propeller 2, so introducing them
Even if they are not directly on the feature map, they are avail- “On-Demand”. The next step will be a short look at the development
able. With this approach we will be able to output an HDMI signal environment and getting our first I/O pin to drive an LED.
directly to a monitor and display content from a flash chip. But 200479-01
that is planned for the end of this series. As an introduction to
Raspberry Pi
Compute Module 4
(CM4)
Price: from €29.95
www.elektor.com/19447
BBC micro:bit v2
Price: €19.95
Member Price: €17.96
www.elektor.com/19488
www.elektor.com/19422 www.elektor.com/19429
www.elektor.com/19525 www.elektor.com/19521
The Hexadoku puzzle employs numbers in the hexadecimal range A number of clues are given in the puzzle and these determine
0 through F. In the diagram composed of 16 × 16 boxes, enter the start situation.
numbers such that all hexadecimal numbers 0 through F (that’s
0-9 and A-F) occur once only in each row, once in each column Correct entries received enter a prize draw. All you need to do is
and in each of the 4×4 boxes (marked by the thicker black lines). send us the numbers in the gray boxes.
PRIZE WINNERS
The solution of Hexadoku in edition 6/2020 (November & December) is: F1235.
The store vouchers have been awarded to:
Huub Liebregts, G.D. (Joe) Young, Jean-Claude Carré, Ralf Boldt Velbert and R. Torfs.
Congratulations everyone!
The competition is not open to employees of Elektor International Media, its subsidiaries, licensees and/or associated publishing houses.
My team is ready to help in both scenarios. Be it with compact but highly efficient content
marketing strategies or complete multichannel campaigning to take advantage of that
new opening in the market, Elektor Helps. These times call for a custom approach for our
clients, and we are going that extra mile. In fact, we are convinced that, together with you,
we can make the difference.
Contact us at www.elektor.com/helps-clients
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
www.elektor.com/member