Professional Documents
Culture Documents
Circuit Cellar - 10 2023
Circuit Cellar - 10 2023
OCTOBER 2023
circuitcellar.com ISSUE 399
TINY
nun linn ■m
2 CIRCUIT CELLAR * OCTOBER 2023 0 9 9
Is s u e 3 9 9 O ctober 2 0 2 3 J ISSN 1 5 2 8 -0 6 0 8
Systems That Save Lives payable in US funds only via Visa, M asterCard, international
postal money order, or check d ra w n on US bank.
DBS is a surgical procedure that places a device called a neurostimulator in the Mail: C ircuit Cellar, PO Box 417, Chase <Jty, VA 23924
wife lovingly teased her mom that she's a robot now. You probably know where this PO B o x 417
Chase City, VA 23924
is going. My Circuit Cellar editor brain lit up when I saw that glowing pack around Phone: 434-533-0246
her neck. While a tremendous amount of credit must go to the numerous doctors
and medical researchers who developed the DBS procedure, I realized some unsung
COPYRIGHT NOTICE
heroes here—and of countless other modern medical procedures—are the embedded
systems engineers who designed, built, and programmed the devices involved. E n tire c o n te n ts c o p y rig h t © 2 0 2 3 by KCK Media C orp.
The neurostimulator, also referred to as the implantable pulse generator (IPG), A ll rig h ts re se rve d . C irc u it C e lla r is a re g is te re d tra d e m a rk
o f KCK Media C orp. R e p ro d u ctio n o f th is p u b lic a tio n in
consists of a battery and power module, CPU and program memory, and a w h o le or in p a r t w ith o u t w r it t e n co n se n t fro m
microprocessor (MPU) to manage device activation/deactivation, pulsing parameters, KCK Media C orp, is p ro h ib ite d .
internal diagnostics, and communication with external devices [1]. How precise, how
carefully tested this embedded system must be! I can only imagine the years of DISCLAIMER
experience and depths of expertise needed to take on such a challenge as a design
KCK Media Corp, makes no w a rra n tie s and assum es no
like this one, where lives hang in the balance. It's brought me to reflect more broadly
responsibility o r liability o f any kind fo r e rro rs in these
on how so much of our modern lives depend—critically—on the tiniest devices, no p rogram s o r schem atics o r fo r th e consequences o f any such
less sophisticated for their size. And so I applaud you, readers, for your passion and e rro rs p rin ted in C irc u it C e lla r® . F urth erm ore, because of
possible v a ria tio n in th e q ua lity and co n d itio n o f m ate ria ls and
dedication to this underappreciated, crucial discipline. Thank you for keeping our
w orkm anship o f reader-assem bled projects, KCK Media C o rp ,
world spinning. And thank you for reading disclaim s any responsibility for th e safe and p ro pe r fu n c tio n
o f reader-assem bled projects based upon o r from plans,
1| S a r it a , Can e t a l. " I m p la n ta b le Pulse G e n e ra to rs f o r Deep d escriptio ns, o r in fo rm a tio n published in C irc u it C ellar® .
B ra in S t im u la tio n ; C ha lle n ge s, C o m p u ta tio n s , a nd S tra te g ie s fo r
P r a c tic a lity a n d L o n g e v ity /’' F ro n tie rs in H u m a n N e u ro s c ie n c e , The in fo rm a tio n provided in C ircuit C e lla r® by KCK M edia
V ol. 15, 2 0 2 1 , h ttp s ://d o i.o rg /1 0 .3 3 B 9 /F n h u m .2 D 2 1 .7 0 B 4 B l. Corp, is fo r educational purposes. KCK M edia C o rp , makes
no claim s o r w a rra n ts that readers have a rig h t to build
things based upon these ideas under patent o r o th e r
relevant intellectual p ro p e rty law in their ju ris d ic tio n , o r
th a t readers have a rig h t to co n stru ct o r o pe ra te any o f
th e devices described herein under th e relevant patent or
o th e r intellectual p ro p e rty law o f th e reader's ju ris d ic tio n .
The rea de r assum es any risk o f in frin g e m e n t lia b ility for
c o n s tru c tin g o r o pe ra tin g such devices.
OUR NETWORK
Renesas 49
TECHNOLOGY FEATURE
STMicroelectronics 55
Tiny Embedded Boards By Michael Lynes
TDK C3
DATASHEET
NOT A SUPPORTING MEMS Sensors
COMPANY YET? They Sense Just About Everything
Contact Hugh Heinsohn
By Sam Wallace
hugh@circuitcellar.com,
Phone: 757-525-3677,
Fax: 888-980-1303 Start to Finish
to reserve space in the When Technology Goes Wrong
next issue of Circuit Cellar.
How Bad I t Can Get, and What You Can Do About It
THE TEAM By Stuart Ball
Raul Alvarez-Torrico
n this three-part article series, I discuss can be helpful for an embedded developer, for
backend web development for embedded prototyping web applications that store and retrieve
clients, such as microcontrollers (MCUs) loT data from a web server using databases, and for
and other edge processors for Internet-of- other applications.
Things (loT) applications. I describe how to set up To be able to follow the topics discussed in this
a web server with a database to develop backend article series, you will need to have some experience
applications for receiving sensor data from remote with the Arduino platform. It is also desirable to
devices via Hyper Text Transport Protocol (HTTP) have some experience setting up server software
requests. The received data are parsed, processed, (Apache, PHP, MariaDB, PhpMyAdmin) on a single
and stored in a database using the PHP scripting board computer (SBC), such as the Raspberry Pi
language. board, or any conventional personal computer. I will
Sensor data are sent from the MCU client as not be covering in great depth how to do the latter,
a string of Comma Separated Values (CSVs). The but I will describe the main steps in reasonable
JavaScript Object Notation (JSON) data-interchange detail. Nevertheless, it's a simple procedure and
format can be used as well. The receiving PHP script there are also countless tutorials on the Web
running on the server processes the data and stores covering the topic. It is also possible to just use a
them in a database. Another PHP script is used to typical shared web hosting service to avoid setting
query the database and extract data matching a up your own server.
certain criterion, such as a given period of time. The The code referenced throughout this article is
script prepares the available results as a JSON or available on the Circuit Cellar Article Materials and
Extensible Markup Language (XML) file, and sends it Resources webpage.
back to the HTTP client that made the request—for
instance, a web browser that requested the data to FULL-STACK WEB DEVELOPMENT
visualize them graphically in a web page. Let's begin by explaining "full stack web
Although there are cases in which Message development," to establish a clear conceptual
Queuing Telemetry Transport (MQTT) protocol base for all that will be discussed in this article.
would be a better option to send loT data to a web "Full stack" refers to the development of both the
server, sometimes edge devices need to interact "frontend" (client side) and "backend" (server side)
with servers that understand only HTTP and secure portions of a web application [1]. Full-stack web
HTTP (HTTPS). However, web clients such as web developers can design and implement complete
browsers generally access server data using HTTP/ web applications or websites, because they have
HTTPS almost exclusively. With that in mind, knowing the knowledge to work on both the frontend and
about servers, HTTP and backend technologies the backend. They also know how to use databases
circuitcellar.com
scripting language. HTML and CSS are not that gathers sensor data and sends them
strictly programming languages; rather, periodically to the web/application server. The
they are markup and stylesheet languages, server receives these data and stores them in
respectively. Additionally, there are some a database. Data are sent by the client (the
frontend frameworks and libraries, such as: MCU) via periodic HTTP POST request to the
AngularJS, ReactJS, VueJS, Bootstrap, jQuery server. To retrieve data from the database,
and SASS, among others. Data exchange any client (for example a web browser or the
formats such as JSON and XML, along with MCU, itself) can send HTTP GET requests to the
query languages such as GraphQL are used server as well. Both types of requests (POST
by web clients to request data from servers. and GET) are part of the REpresentational
The backend is the non-visible, server State Transfer (REST) architectural style, on
side part of the web application or website, top of which most Internet websites are built.
and it defines how the website works for the The data are transferred from the client
most part. It is also responsible for managing to the server using data interchange formats
the database, and interacts with it on behalf such as CSV, JSON or XML. In general, CVS
of web clients. To this end, it provides and JSON are the most efficient in terms
Application Programming Interfaces (APIs) of memory space, because they use less
to the client side. Backends are typically built metadata for data representation. However,
using languages such as PHP, Ruby, C++, to retrieve data from the application server,
Java, Python, JavaScript/NodeJS, and others. JSON and XML are typically used, especially by
Some frameworks, including Express, Django, more conventional web clients, such as web
Rails, Laravel, and Spring, also are available. browsers. For MCU clients requesting data
Databases are also part of almost any backend. from the application server, JSON is more
Popular database technologies used are Oracle, efficient in comparison with XML, in terms
MongoDB and MySQL/MariaDB, among others. of memory. CSV can also be used, which is
There are also some popular technology even more efficient; but at the same time, it
stacks used for backend development. They has its drawbacks—being less clearly defined,
include MEAN (MongoDB, Express, AngularJS, not hierarchical and not easily scalable in
and Node.js), MERN (MongoDB, Express, comparison to JSON and XML. Nevertheless,
ReactJS, and Node.js), Django (Django, CSV can be convenient for small datasets.
Python, and MySQL), Ruby on Rails (Ruby,
PHP, and MySQL) and LAMP (Linux, Apache,
MySQL, and PHP).
Front End Back End
In this article series we will use LAMP,
because it is arguably the most popular and MySQL/
PHP MariaDB
is commonly found. For instance, most of the
shared hosting servers offer LAMP installed by
default, so you don't need to install anything
else to begin developing web applications.
BACKEND WORKFLOW
Let's describe a typical backend workflow
Client Web/Application Database
for a simple loT web application. Figure 2 is a Server
conceptual diagram of this type of workflow.
For the purpose of this article, the web
client will be primarily any edge device. For FIGURE 2
the concrete application example we will Backend workflow for an loT web application.
CIRCUIT CELLAR • OCTOBER 2023 #399
WEB AND APPLICATION SERVER Radxa RockPro64, Nano Pi R4S, and others.
To build your first HTTP loT web application, Moreover, any regular Linux computer or
there are two easy options for setting up an laptop can also be used. A computer with the
application server. The first one is to use an Windows operating system can be used after
SBC, such as the Raspberry Pi board, as a installing WAMP (Windows, Apache, MySQL
server, and to install on it the LAMP stack. and PHP) or Laragon [2].
Other SBCs can be used as well, for instance, The second option is to use a regular
boards such as the Orange Pi, Le Potato, shared hosting server. Most cheap web
Asus Tinker Board, Odroid N2+, Banana Pi, hosting options (around $10 a month) come
with the LAMP stack installed by default. The
user doesn't have to install anything else to
1 # Setting Up a LAMP Web Server On A Raspberry Pi be able to write web applications using PHP
2 and MySQL/MariaDB databases.
3 ## Step 1: Update Your Operating System In this article, we will use the first option,
4 sudo apt update and I will describe the main procedure to set
5 sudo apt upgrade up a Raspberry Pi server. I will not go into
6 great detail, but the procedure is fairly easy
7 ## Step 2: Install and Test Apache Server for someone that has reasonable experience
8 sudo apt install apache2 using a Raspberry Pi and the Linux terminal.
9
10### Find your Raspberry Pi IP address: RASPBERRY PI SERVER
11 Hostname -I Setting up a Raspberry Pi web server is
12 relatively easy. The procedure described
13### Open the IP address on your web browser. For next assumes you have already installed the
example: http://192.168.0.100 Check that the “Apache2 Raspberry Pi OS on your board. The same
Debian Default Page” is shown. steps will work equally well with other Debian
14 based operating systems, such as Armbian
15## Step 3: Install and Test PHP and Ubuntu. Listing 1 shows the commands
16sudo apt install php 1ibapache2-mod-php to run on the Linux terminal to install the
17 LAMP stack [3].
18### Test your first PHP script. Go to the Apache web As a first step, it is a good idea to update the
folder: operating system by running the commands
19cd /var/www/html from lines 4-5. Next, install the Apache web
20 server software by running the command
21### Create a new PHP file: in line 8. After the installation finishes, you
22sudo nano test.php will be ready to test Apache. Make sure your
23 Raspberry Pi is connected to your local LAN
24### Copy this code into it: via Ethernet or Wi-Fi, and get the IP address
25<?php phpinfo(); ?> assigned to it by running the command in line
26 11. Open that IP address on a web browser
27### Open the script on your web browser. For and check that the default "Apache2 Debian
instance: http://192.168.0.100/test.php Check that the Default Page" loads on the web browser page.
default PHP Info “PHP Version x.x.x” is shown. It should look like the screenshot in Figure 3.
28 Next, run the command in line 16 to install
29## Step 4: Install and Test MariaDB PHP and the Apache plug-in that interprets
30sudo apt install mariadb-server php-mysql PHP files. After the installation, you can test
31 it with a simple PHP script. Go to the server's
32### Restart Apache: root folder (line 19), create a "test.php" file
33sudo service apache2 restart (line 22), and write in the PHP code from line
34 25. Line 22 uses the "nano" terminal-based
35### Check that MariaDB is installed properly. Start text editor to edit the aforementioned PHP
Mari aDB: file, but you can use any other terminal-based
36sudo mariadb or Graphical User Interface (GUI) text editor.
37 Next, open the PHP script on a web browser
38### List all available databases: (see line 27). If PHP is set up correctly, you
39show databases; should see a webpage similar to the one
40 shown in Figure 4.
41### Exit MariaDB: As one of the last steps, install the MariaDB
42exit database by running line 30. For practical
purposes, MySQL and MariaDB are the same
LISTING 1
database. MariaDB is an improved, open-
Raspberry Pi web server installation. source fork, backward-compatible version of
circuitcellar.com
1 i n c l u d e <ESP8266WiFi .h>
2 # d efin e PUB_INTERVAL 5000 / / Data p u b lic a t io n in t e r v a l (msec)
3
4 char* s s id = “ M yW iFi” ;
5 char* password = “ MyCatKnowsAssembly” ;
6
7 W iFi C lie n t c l i e n t ;
8 char s e rv e r_ a d d r[] = “ 1 9 2 .1 6 8 .0 .1 5 ” ; / / S e rve r IP addres
9 char p h p _ s c r ip t _ u r i[] = “ / b a c k e n d /re c e iv e _ c s v . php” ; // URI f o r the PHP s c r ip t th a t w i l l
re c e iv e and p ro cess the data
10 S t r in g csv_ d a ta ; // CSV data s t r in g to send to the s e rv e r
11
12 vo id s e t u p ! ) {
13 S e ri al . begin (115200); // Open the A rd u in o s e r ia l te rm in a l
14 w h ile ( I S e ri a l );
15
16 // Connect to Wi Fi
17 S e ri a l . p r i n t ( “ Connect! ng to : “ );
18 S e ri a l . p r i n t l n ( s s i d );
19 W iF i.b e g in ( s s id , passw ord);
20 w h ile (W iF i. s t a t u s () != WL_CONNECTED) {
continued
LISTING 2
MCU web client Arduino source code.
circuitcellar.com 9
terminal for debugging purposes. Line 44 will print the incoming server response after
calls the Send_Http_Request() function attending the HTTP POST request.
that's in charge of sending the CSV data to the Lines 55-74 show the Send_Http_
web server by issuing an HTTP POST request. Request () function definition. After creating
Line 45 takes the current system time a connection to the server (line 56), lines
in milliseconds to restart the time count for 59-68 send the HTTP POST request header. F
E
the next publication interval. Lines 48-51 Line 69 separates the header from the body, A
T
U
R
E
S
21 delay(500); LISTING 2
continued
22 Seri al.pri nt(“ .”);
23 }
24 Seri al.println(“WiFi connected. IP address:” );
25 Seri al.pri ntln(Wi Fi.1ocal IPC));
26 }
27
28 void 1oop() {
29 static long prev_mi11is; // Stores time of the last publication
30 // Generate random values to simulate sensor readings
31 float gas_resistance = randomCO, 100);
32 float pressure = random(0, 100);
33 float temperature = randomCO, 100);
34 float rel_humimidy = randomCO, 100);
1 <?php
2 $csv = fi1e_get_contents(‘php://inpUt’); // Get the body (CSV string) from the incoming request
3
4 echo “Received CSV string: // Send back received data to client just for debugging
S 5 echo $csv . “\n” ;
E
R 6
U
T 7 $data_array = str_getcsv($csv); // Convert CSV to array
A
E 8
F
9 if($data_array != null) {
10 $unix_t = timeO; // Read unix time (GMT) from server
11
12 // Extract received remote values from array
13 $gas_res = $data_array[O];
14 $pressure = $data_array[l];
15 $temperature = $data_array[2];
16 $rel_hum = $data_array[3];
17
18 // Build SQL query string for the database
19 $query = “INSERT INTO data_logger(unix_t, gas_res, pressure, temperature, rel_hum) VALUES”
LISTING 3
Listing for the "receive_csv.php" php and line 70 sends the CSV data as the body OUR FIRST PHP SCRIPT
script- of the HTTP request. The described structure So, to attend to the HTTP POST requests
follows the HTTP protocol specification. The sent by the MCU client, we need a PHP script
Circuit Cellar Article Materials and Resources that will run on the server every time those
webpage includes a link to an explanation requests arrive. Remember from the MCU
of HTTP protocol basics, in case you are not client's Arduino code that the URI for this PHP
familiar with it [6]. script is included in the HTTP header. So, now
Note that line 60 inserts in the header we need to create a "receive_csv.php" script
the Uniform Resource Identifier (URI) of the and put it inside a "backend" folder in the
PHP script on the server that will receive and server's root directory. Listing 3 shows the
process the data. The php_script_uri PHP code for the aforementioned script.
variable is defined in line 9. The URI string PHP code must be surrounded by an
7backend/receive_csv.php" specifies that opening tag, as shown in line 1 (<?php), and
the request is directed to a "receive_csv. a closing tag as shown in line 24 (?>). For
php" script inside a "backend" folder in the the most part, PHP is similar to C and C++
server's root directory. Line 63 inserts the languages. However, all variable names in PHP
web server's IP address defined in line 8. must begin with the character. In line 2
of Listing 3, the fi 1e_get_contents PHP
function reads from the server system the
Additional materials from the author are available at: incoming HTTP request's body, which, if you
www.circuitcellar.com/article-materials remember, contains the CSV string with the
References [1] to [7] as marked in the article can be found sensor readings. In the same line, this CSV
there. string is stored in the $csv variable.
Lines 4-5 send back debugging data to the
RESOURCES
client using the echo "function" (technically,
a "language construct") that is analogous to
Adafruit | www.adafruit.com
the printf C language function. Suppose
Arduino | www.arduino.ee the received CSV string was, for example,
Bosch Sensortec | www.bosch-sensortec.com "49.0,52.0,23.0,30.0"; lines 4-5 will send
back to the client the string, "Received CSV
Espressif Systems | www.espressif.com
string: 49.0,52.0,23.0,30.0\n". The last two
Laragon | laragon.org characters (\n) are the "new line" character
Raspberry Pi | www.raspberrypi.org that makes the cursor jump to the next line
circuitcellar.com
in the screen. The '.' character in line 5 is the applies to other Debian-based distributions,
PHP string concatenation operator. See as such as Armbian and Ubuntu. Download
well that in line 22 we have another e c h o . all source code files from the Circuit Cellar
All strings from these e c h o construct callings Article Materials and Resources webpage.
will be included in the HTTP response's body Then, copy the "receive_csv.php" script to
that the server will send back to the client. the "backend" folder and make sure the file
Line 7 uses the s t r _ g e t c s v PHP function has the right access permissions. For setting
to parse the CSV string and store the result the permissions open a terminal window on
to the $ d a t a _ a r r a y array. The cells in the the "backend" folder, and run the command:
resulting array will contain the individual chm od 644 r e c e iv e _ c s v . p h p
sensor values that were separated by commas Next, connect the ESP82266 board to
in the received CSV string. Line 9 checks that your PC, and upload the "esp8266_http_post_
the conversion operation was successful and client.ino" Arduino sketch. Before flashing
the resulting array is not null. If so, in lines your board, don't forget to change lines 4-5
13-16 the array is indexed to read all sensor with your Wi-Fi credentials and line 8 with
values into local variables. But previously, the IP address assigned to your server. After
in line 10, we read the "Unix time" from the flashing the board, it will reset itself and try
server system and stored it into the $ u n i x _ t to connect to your Wi-Fi network. Open the
variable. Arduino IDE's serial monitor to see debug
In case you are wondering, Unix time is information. Once the board is connected
a way of representing a timestamp as the to your Wi-Fi, it will automatically start to
number of seconds since January 1, 1970 send data periodically to the web server. A
at 00:00:00 UTC. Unix time timestamps are response from the server, similar to what
represented as integers, which makes them is shown in Figure 7, will be printed on the
easier to parse using programming languages serial monitor.
[7]. Here we are using the obtained server
Unix time as a timestamp for the sensor CONCLUSION
readings batch that just arrived. I hope I succeeded in showing you how
Next, in lines 19-20 we build the SQL query relatively easy it is to receive data from an
string that will insert the received values MCU client on a web server, and process
into the database. I will explain MariaDB the data using PHP. To understand the
databases and SQL queries in more detail in workflow, it greatly helps to be fam iliar
Part 2 of this article series. For now, let's just with the client/server model and the HTTP
accept as a fact that these two lines build the protocol. If some concepts are still new
required SQL query to insert the data into and confusing to you, take the time to read
the database, by concatenating two strings the included resources, test the example,
(see t h e '.' at the end of line 19), including the and carefully analyze the provided code.
values stored in variables (line 20). Don't w orry if you still have some lingering
Line 22 echoes the resulting string doubts; just make sure you understand the
contained in the $ q u e r y variable to the general workflow, and give yourself some
client. The string will look like this: extra time to understand the details.
In Part 2 of this article series, I will
INSERT INTO d a t a _ lo g g e r ( u n ix _ t , explain how to create a database and store
g a s_ re s, p re ssu re , te m p e ra tu re , the received data in it, using a slightly
r e l_ h u m ) V A LU E S ( 4 9 . 0 , 5 2 . 0 , 2 3 . 0 , 3 0 . 0 ) modified version of the PHP script described
here. I will also explain how to extract data
The names inside the first parentheses from the database and send it back to a web
are column names in the "datajog ger" client using a second PHP script. We will
database table. The values inside the second also explore the pros and cons of using
parentheses are the corresponding values to different data exchange formats, such as
be inserted in each column. For now, we are CSV, JSON, and XML.
just showing how to create the SQL query, but
we are not using it yet. We will do that in Part
2 of this article series. ABOUT THEAUTHOR
Raul Alvarez-Torrico has a BEng in e le ctro n ics and is the fou n d er
RUNNING THE FIRST TEST of TecBolivia, a com pany offering services in physical com puting and
Let's describe now the procedure to run educational robotics in Bolivia. In his spare time, he likes to experim ent
a first test with all that we have ready. First, with wireless sensor networks, robotics, and artificial intelligence. He is also
create a "backend" folder inside your web committed to publishing articles and video tutorials about embedded systems
server's root directory. On a typical Raspberry and programming in his native language (Spanish), at their company's site
Pi server installation, the server root directory www.TecBolivia.com. You may contact him at raul@tecbolivia.com.
will usually be: "/var/www/html." The same
12 CIRCUIT CELLAR • OCTOBER 2023 #399
zram m
Embedded Linux
S
E
How to Maximize RAM in a
R
U
T
A
E
F
Linux Environment
By
Pedro Bertoleti
In this piece, I discuss how to use zram for memory swap, in order to create a drive/
disk that is mounted in RAM memory itself, using on-the-fly data compression and
decompression. This expands the real storage capacity in RAM and significantly
increases write and read speed in swap operations. As a practical example, III
also show how to use zram in a Raspberry Pi single-board computer (SBC).
a mbedded Linux is popular for its significantly increases write and read speed
I flexibility, wide array of supported in swap operations. As a practical example,
hardware, and robustness. But, I'll show how to use zram in a Raspberry Pi
as happens for applications for single-board computer (SBC).
personal computers, the memory footprints
of applications supported by embedded Linux WHAT IS ZRAM?
tend to grow over time—and as a consequence In brief, zram is a Linux OS feature
they demand more RAM memory to work with which you can create a block device
properly. This leads to more memory swap mounted into RAM memory, with on-the-fly
operations, a must-have solution to keep compression (so data can be written into
memory management healthy in embedded zram in compressed form) and decompression
Linux. (so data is automatically decompressed in
However, memory swap has a huge cost zram read operation). Data is automatically
for embedded Linux: it decreases the overall compressed before being stored in zram,
performance of the operating system (OS). and data from zram is automatically
Traditional memory swap operations use a decompressed before being read, too. This
certain portion of a mass storage memory compression-decompression feature gives
(flash memory, SSD, HD, and so forth) to store zram the ability to more data than its real
the less frequently used data. Considering capacity, as all data is stored in a compressed
mass storage memory speed (read and write form.
speed) is much slower than RAM memory Since zram is like a disk or storage
data access speed, every single memory drive mounted into RAM memory, it takes
swap operation suffers from the slowness in advantage of high-speed read and write
writing and accessing data from mass storage operations in RAM. Thus, zram also offers a
memory, which results in overall embedded significantly higher read and write speed than
Linux latency. traditional mass storage memory (especially
This article covers how to use zram for old hard drives).
memory swap, so as to create a drive/disk See Figure 1 for an interesting comparison,
mounted in RAM memory itself, using on-the- the source for which can be found on C ir c u it
fly data compression and decompression. This C e lla r's Article Materials and Resources
expands the real storage capacity in RAM and webpage [1]. As you can see, a RAM disk (or
circuitcellar.com
a multipurpose disk mounted into RAM, such many cases, the right compression algorithm
as zram) can be more than 10 times faster can mean better overall embedded Linux
than a solid-state drive (SSD), and more than performance.
47 times faster than a hard-disk drive (HDD). Increased total swap memory capacity:
zram is, definitionally, a resource that Some compression algorithms offer
allows one to create a compressed device compression rates greater than th r e e -
block into RAM memory. But its enhanced meaning zram can actually store more than
data capacity and data read/write speed three times its real data capacity. This feature
make it the perfect choice for memory in is especially useful in solutions that use a lot
swap operations. In fact, using it as such of RAM memory, like rich user interfaces with
has many advantages. Let's examine some of animations and high-resolution images.
these now.
Faster read/write o f data: Even with PREREQUISITES FOR ZRAM IN
the time spent doing on-the-fly data EMBEDDED LINUX
compression and decompression, zram is To use zram in embedded Linux, some
still a significantly faster alternative to mass prerequisites must be met. These relate to
memory storage. Using zram as memory Linux kernel configurations that enable zram
for swap significantly decreases the general usage, and that indicate which compression
latency seen in embedded Linux when it's algorithms must be integrated into the kernel
in memory swap operation, since the I/O in its compilation. Then, enabling zram and
wait—the time the CPU spends waiting for a its compression algorithms involve Linux
response from an I/O device, such as a block kernel compilation.
device— is much shorter in zram thanks to the If you're not familiar with the Linux kernel
RAM memory speed in data access. Hence, compilation process, Raspberry Pi's website
embedded Linux performance tends to be has excellent documentation detailing the
significantly enhanced, providing a smoother full process for Pi boards [2]. Assuming
experience to the user. In extreme cases, you are familiar, the following Linux kernel
zram can even prevent the memory thrashing configuration settings enable zram to work in
effect, wherein excessive memory swapping an embedded Linux OS:
drastically reduces system performance.
Avoids wearing out flash memory: As • CONFIG_zram: Must be set to y.
discussed, traditional memory swap uses • C0NFIG_zram _LZ4_C0M PRESS: For a
mass storage memory. Nowadays, embedded compression algorithm to be available in
Linux systems usually have flash memory embedded Linux, kernel configs must inform
for mass storage, and this can quickly wear it which compression algorithm to integrate
out with excessive memory swap operations. into the kernel when compiling. For example,
Flash memory becomes unusable, and to make the LZ4 compression algorithm
embedded Linux won't work. With zram for available, CONFIG zram LZ4 COMPRESS
memory swapping, the flash memory isn't must be set to y. Consult Linux kernel zram-
used and is thus preserved—at least, it won't related documentation to see other available
wear out as quickly. compression algorithm options (and their
More flexibility: The way zram compresses corresponding kernel configs).
and decompresses data is governed by a
"compression algorithm." There are multiple
types of compression algorithms available, CONSEQUENCES OF USING ZRAM
enabling developers to test several and As with everything, there isn't a definitive,
choose the best fit for a particular solution. In costless, and miraculous solution for an
• 477.9 235.7
402.7 248.9
M l 30.49 64.67
FIGURE 1
200.3 233.2 A speed comparison between a hard
disk drive, solid-state drive, and RAM
disk drive.
CIRCUIT CELLAR • OCTOBER 2023 #399
FIGURE 2
Free tool output
embedded system problem. There's always • You need access to a terminal in Raspberry
a trade-off. A solution that improves some Pi. This can be done either via a local network
aspects of a system can simultaneously worsen using SSH, or using a physical keyboard,
others. And of course, zram is no different. mouse, and monitor connected to the Pi.
Specifically, zram demands more • Your Raspberry Pi needs Internet access
processing from CPUs. Its on-the-fly to be able to update its packages and to
compression and decompression tasks require download the required software for zram.
extra processing compared to traditional swap
processes (those using mass storage memory Assuming you've already compiled the
for swap). It's a good practice to check CPU Linux kernel with the discussed configurations
usage when using zram, to prevent undesired (the Raspberry Pi OS kernel is already okay),
side effects. I strongly recommend you: the only thing left is to set up zram for
memory swapping.
• Check the overall impact on CPU usage: Can There's an interesting open-source project
the CPU still smoothly run everything? Is available on GitHub that helps in this regard
overall performance significantly worse? [4]. The appropriately named "zram-swap"
• Check the CPU's temperature: More CPU contains useful scripts to prepare a Pi board
usage means a higher CPU temperature. to use zram as memory for swaps without
You'll need efficient heat dissipation when requiring the user to be familiar with memory
using zram. CPU overheating is a big swap setup commands in Linux. I find it's a
problem, and, needless to say, should be practical solution for those who want to
avoided in all real-world implementations quickly verify zram is working for swaps on
of your solution. their Pi. To use zram-swap:
Resources
After finishing these steps, zram should
be working on your Raspberry Pi board as
Raspberry Pi | www.raspberrypi.com memory for memory swap operations.
circuitcellar.com
Evaluating EDATEC's
Line of Industrial Modules
Based On the Raspberry Pi Compute Module 4
S
E
R
U
T
A
After a few years during which all Raspberry Pi boards were
E
F unavailable to me, I was interested in getting my hands on a line
of modules made by EDATEC that are based on the Raspberry Pi
CM4 module. Here's the review.
FIGURE 1
This is a front view of the unit showing all of the terminal blocks, which are used to connect the
various I/O devices. There is a power LED and an activity LED, as well as a recessed Reset switch.
By
Brian Millier
The Industrial contains a single HDMI only able to test the unit in my office, which
video port. It's rated for 4K operation and, has seen ambient temperatures in the high
while it's unlikely to be used this way in an 20s Celsius due to our hot summer weather.
industrial setting, I tried it out on my 4K The steel enclosure did not seem to get much
computer m onitor and it worked properly. hotter than the ambient room temperature
For industrial purposes, it's more likely that under normal operating conditions, and the
a smaller TFT panel would be needed. This CPU temperature widget on my toolbar showed
module contains the standard DSI connector CPU temperatures in the high 40s Celsius. In
found on the Raspberry Pi boards, and which contrast, the EDATEC CM4 Media module, which
is compatible with the official Raspberry Pi is enclosed in a small CNC-machined aluminum
TFT touchscreen display. It also contains a case, gets pretty warm to the touch. However,
separate FPC HDMI connector which supports its CPU temperatures are comparable to what
a second HDMI screen plus a USB-based touch I see on the CM4 Industrial.
controller. These two connectors would only At the other tem perature extreme, there
be readily accessible if you purchased the CM4 are two different CM4 Industrial model
Industrial w ithout an enclosure and custom- variations: one fo r 0°C —►50°C and another
housed it yourself. for -25°C 50°C.
There are slots available on the back panel Earlier, I mentioned that the CM4 Industrial
to accommodate a pSD card as well as a SIM module is powered by 12V via a barrel socket.
card. While the slots/sockets will be present I used the ED-PSU1202 DC adapter module
on all models, they are only operational in the that was sent along w ith the CM4 Industrial.
following scenarios: This supplies 12V at 2A. Earlier versions of
the CM4 Industrial (V I.1 to V I.3) were rated
• The pSD socket can only be used when for an input range of 9V-18V. However, 24V
eMMC memory is not mounted as the is commonly used in industry, so the newer
system Flash memory. You can't use both. versions (V1.4 onward) are now rated for
• The SIM card is only active if you have 9V-36V. The unit I received came in a box
installed a 4G/LTE modem module. showing exactly what options were present
(memory, Wi-Fi, cellular), but neither the
I like the fact that the CM4 Industrial box nor the unit's enclosure contained either
can be purchased with 8, 16, or 32GB of a serial number or the hardware version
eMMC flash (as well as an option w ith no number. However, the revision level is clearly
eMMC, but using a pSD card for program shown on the PCB itself. Figure 3 is a photo
memory). Early adopters of the Raspberry Pi of the top of the CM4 Industrial's PCB; the
sometimes experienced SD card corruption revision number is located to the right of
when power was removed unexpectedly from the A26 socket. The purpose of each of the
the Raspberry Pi. While the Raspberry Pi OS Axx legends is described in section 1.4 of the
has improved somewhat in this regard, the user manual [1]. The CM4 Industrial module's
problem still exists that pSD cards, even when power supply is capable of providing a 5V at
labeled w ith reputable brand names, can be 1A output on the 2-pin header labeled A24.
poor-quality clones. The eMMC memory is When I checked, all of EDATEC's CM4
more reliable. modules contained a Mini PCIe socket. This
The CM4 Industrial can be ordered with
1, 2, 4, or 8GB of RAM memory. Actually,
Flash size, RAM size, and Wi-Fi/Bluetooth
functionality are all dependent upon which
CM4 module is mounted in the unit. As the
CM4 is a socketed device and is available
from Raspberry Pi distributors/retailers, it
would certainly be possible to upgrade a CM4
Industrial module post-purchase, if needed.
The CM4 Industrial comes in a steel
enclosure w ith a reasonable amount of cooling
vents. The CPU and other heat-producing chips
contained on the CM4 SoM are coupled to this
steel enclosure via therm al pads. There is no
fan included with this unit, although there
is an adjustable speed fan control circuit on
the PCB and a 3-pin socket fo r a tachometer
fan. The CM4 Industrial is available w ithout FIGURE 2
an enclosure and presumably that is when This is the rear view of the unit. This contains two USB, two Ethernet, and an HDMI port that are normally
the fan and controller m ight be utilized. I was used to connect to a keyboard, monitor, and network connections.
18 CIRCUIT CELLAR • OCTOBER 2023 #399
can be used to add a cellular modem or SSD. I • HDMI port via an FPC socket with I2 C port
was in an unusual position because I received for touchscreen controller
both a CM4 Industrial and a CM4 Media unit, • One DSI display port
and it's unlikely any one customer would order • Two externally-accessible USB 2.0 type A
both. While reading the Media's documents, ports
S
I noticed that it could handle an SSD with a • Raspberry Pi standard 40-pin GPIO
E Mini PCIe interface. After ordering such an connector (on the internal PCB)
R
U SSD, I discovered that the CM4 Industrial unit
T
A
E
F can handle a cellular modem in this Mini PCIe There is an additional Micro USB socket,
socket, but not an SSD. This seemed unusual accessible only with the enclosure removed.
to me, but the CM4 Media block diagram This is used solely to program the eMMC flash
shows the Mini PCIe socket connected to the (assuming the CM4 module contains eMMC).
BCM2711's PCIe bus via a USB3 hub with an This should be hidden, as you don't want a
mSATA port. In the case of the Industrial, port that can reprogram Flash to be readily
the PCIe socket connects to the BCM2711's observable or accessible.
PCIe port directly. In any case, the new SSD I Having a few more USB ports might be
purchased works fine in the CM4 Media. useful—there are two header footprints
on the PCB: USB6 on A12 and USB5 on A13
INDUSTRIAL-PURPOSE INPUTS/ (Figure 3). I wired up header pins and a cable
OUTPUTS to these footprints, and these extra USB ports
The CM4 Industrial module comes with the worked fine.
following standard I/O ports: Let's take a closer look at the I/O targeted
for Industrial purposes. The system diagram
• Two channels of Digital Input (optically in the user manual gives a block diagram
isolated) of all of the circuitry in the CM4 Industrial.
• One Digital Output (DPDT relay 125V, 1.5A I wasn't supplied with a schematic diagram,
contacts) but a close inspection of the board allowed
• RS-232 Serial port (±5V signal levels) me to draw Figure 4, which shows what ICs
• Two RS-485 ports (half-duplex) are used for these I/O ports, as well as which
• One ADC (TI ADS1015 with three of four BCM2711 port drives them.
channels available) The CM4 Industrial datasheet lists part
• Two CSI Camera ports (supports official numbers 2EDGR-2.5-XP/15EDGRC-2.5-XXP -1 4 -
Raspberry Pi 5/8/12 Megapixel cameras) 00AH for the various input/output removable
• One HDMI port (4K-capable) terminal blocks on the front panel (where X
or XX are the number of terminals). The unit
comes complete with these pluggable terminal
A1 A2 A3 A4 AS A6 A7 A8 blocks. The sockets and pluggable terminal
blocks are made by Degson and have a spacing
of 2.5mm between pins. The supplied terminal
blocks have pushbuttons that, when pressed,
allow the wire to be fully inserted and locked in.
I believe that the part number quoted above is
a combination of both the socket and pluggable
terminal block, but I couldn't find that exact
number for the terminal blocks on Degson's
site. However, Degson does carry 15EDGK-
2.5-XXP-10020000066 parts that are identical
to the terminal blocks supplied with the CM4
Industrial (again, the XX is the number of wire
terminals contained in the block).
Digital Inputs: Each of the two digital
inputs consists of a TLP185 optocoupler
connected to a specific BCM2711 GPIO pin.
The Digital Input connector contains six pins,
two of which are +12V and Ground. You can
use this 12V supply, along with switches and
so on, to drive the TLP185 opto-coupler. While
EDATEC shows a resistor divider network,
A22 A21 A20 A19 A18 A17 as shown in Figure 4, they didn't provide
any resistance values. They did state that a
FIGURE 3 voltage of 3V or greater across the DI+, DI-
This is the top side of the PCB. The "Axx" labels are described in section 1.4 of the User Manual. terminals will activate the optocoupler, but
circuitcellar.com
not much else. I wanted to know more, so GPIO22. This is not a particularly heavy-duty
I performed some actual measurements relay: the contacts are rated at 2A at 30VDC or
and determined that the equivalent internal 1.5A at 125Va c . The labeling on the front panel
resistance in series with the TLP was about uses " 0 " for the N.O. contacts, "C" for the N.C.
4700. I also found that 4V (not 3V as stated) contacts, and "W" for the moveable contacts.
was needed across DI+/DI- to activate The relay output can be easily tested using
the TLP185 in my unit. Given the TLP185 the following commands from the CLI:
datasheet and the approximate 4700 internal
current-lim it resistors, you can calculate what sudo r a s p i- g p io s e t 22 op dh
size external current-lim iting resistor would (opens the relay)
be needed if you're dealing with higher input sudo r a s p i- g p io s e t 22 op dl
voltages. These inputs can be tested using the (closes the relay)
following commands from the CLI (that is, a
term inal window): Here again, this uses the negative-logic
convention.
r a s p i- g p io g et 11 (DINI) RS-232: The front panel RS-232 connector is
r a s p i- g p io g et 26 (DIN2) driven by a Sipex SP3232 RS-232 interface chip.
This device contains its own charge pumps to
When 4V or more are applied to either provide the ±5V RS-232 signal levels. As far as I
digital input, the level value that is returned can tell, there are no hardware handshake lines
will be 0—otherwise it's a 1 (in other words, available for this port. UART5 on the BCM2711
negative-logic). drives this port. I tested it with the Minicom
Digital Output: The digital output consists Serial terminal program—the RS-232 port is
of a single DPDT relay that is activated by device /dev/ttyAMA3 in the Linux OS.
Buzzer
USER BUTTON
ON: sudo r a s p i- g p io s e t 25 op dh
OFF: sudo r a s p i- g p io s e t 25 op d l
r a s p i- g p io g e t 6
which returns: GPIO 6: level=X fsel=0
func=INPUT pull=UP
FIGURE 6
This is a scope capture of a 5.1KB file being transmitted via RS-485. The 450ms time that it took for the where X=1 if the switch is NOT pressed, X=0
transfer matches the 115,200 baud rate that I was using. if it is (negative-logic used)
circuitcellar.com
The CM4 Industrial's PCB contains a few crosses a threshold (a window mode is also
header pin footprints that are not mentioned available)
in EDATEC's documentation. There is a 4-pin • A wide supply range of 2.0V to 5.5V
footprint with labels for 3.3V, GND, ANO, and • I2 C interface (up to 400kHz in standard
AN1. I am not sure what they are for. mode, up to 1MHz in high-speed mode)
There are also pinouts for SYNC IN and
SYNC Out. While these are not mentioned I've used this particular ADC many times
anywhere in the documents, I know from the in the past and find it to be accurate and
Raspberry Pi CM4 technical reference that versatile. In the CM4 Industrial, only AIN1
they are 1.8V signals to support IEEE 1588-
2008 [2]. This is a feature that allows for a
1V3 445wi
high-precision clock synchronization protocol
derived from the Ethernet signal itself.
Analog Input: The CM4 Industrial
contains three channels of analog input. This
is handled by a Texas Instruments ADS1015
which contains the following features:
A \ M ic r o c h ip
CIRCUIT CELLAR • OCTOBER 2023 #399
through AIN3 are brought out to the Analog channel, you just perform a file read on
terminal block. For some reason, AINO is not the file "in_voltageX_raw" where "X" is the
available. This reduces the single-ended input channel number (other files are present for
choices to three and the differential input the differential readings as well). Note that
choices to two. these files are labeled in the same way that
The ADS1015 is a single-supply ADC. I the ADS1015 datasheet uses. That is, they
don't see any sign of logic-level translators range from channel 0 through channel 3. So,
near this chip, so I assume it's powered for example, you can read the ADC channel
by 3.3V, as that is the logic level expected labeled AIN1 on the front panel by issuing the
by the BCM2711. That means that the following command from the CLI:
ADS1015's analog input signals must remain
between ground potential and 3.3V. For the cat in_voltagel_ raw
single-ended input mode, this means that
only positive voltages in this range can be As mentioned earlier, the ADS1015 CHO is
measured. If you configure the ADS1015 for not brought out to the Analog terminal block.
differential input measurement, then bipolar Also present in this folder is a series of files,
signals can be measured, but only if they one for each ADC multiplexor channel (single-
ride on a common-mode voltage that keeps ended and differential) that end in the word
the signal peaks within the OV to 3.3V range. "scale." If you examine any of those files,
Given this limitation, the ±6.144VFS scale can you'll see that they contain the single number
be used but you will never see any readings 3.00000. This corresponds to the number of
beyond about half-scale. millivolts per LSB, expressed in millivolts.
I asked EDATEC whether there was any In this case, 3mV corresponds to a full scale
protection circuitry present for the ADS1015 of 0.003 x 4096 = 12.288V. However, since
inputs A1-A3. They replied that the ADS1015 the ADS1015 provides bipolar readings, this
itself has ESD ratings of ±2000V HBM model corresponds to a VFS of ±6.144V. For other full-
and ±500V CDM model. These figures are scale ranges, you can change this entry, as
from TI's datasheet. No additional circuitry shown in Table 1. When I tested the ADS1015
is present. However, you cannot apply any in the CM4 Industrial module, even on the most
sustained voltage to any of the ADS1015's sensitive (±0.256 V) scale, I only observed one
analog inputs outside of the GND-0.3V to LSB variation in the results, with the input
Vc c +0.3V range, so I would be careful to allow voltage held constant. From experience, I also
for this in any external circuits that might be know that each of the available PGA gains are
connected up. exactly a factor of 2.00 apart, so you can do
I am accustomed to using the ADS1015 in things like auto-scaling easily without any
"C" or Python programs. In these cases, you per-range calibration factors needed.
interact with the ADS1015 via a driver library Similarly, there are a series of files
that is written in "C." With the Linux operating ending in "sampling_frequency." The number
system present on the CM4 Industrial, contained in these files can be read and/or
controlling and reading the ADS1015 is changed to the following sample rates: 128,
done much differently. Texas Instruments 250, 490, 920, 1600 (default), 2400, and 3300
provides a Linux driver for the ADS1015 samples per second. I doubt that the Linux
using the device tree. However, there was driver can handle the higher rates, however.
not enough information on TI's website for The ADS1015 is capable of responding to I2 C
me to determine if that is what is used on addresses of 0x48, 0x49, 0x4A, and 0x4B,
this module. However, if you navigate to the depending upon how its Address pin is
following folder: strapped. In the CM4 Industrial, it responds
to the default I2 C address of 0x48.
/sys/bus/iio/devices/deviceO I have not found any evidence that the
supplied ADS1015 Linux driver can handle the
you will see a whole series of files. To read comparator function that I mentioned earlier,
the voltage present on a specific ADC but I could be mistaken about this.
Raspberry Pi 40-Pin GPIO header: This
unit contains a footprint for the standard 40-
pin GPIO header found on all recent Raspberry
Pi modules. You should note, however, that
a number of these GPIO pins are already
allocated to internal functions: GPIO 6, 26,
and 11 are some examples.
TABLE 1 RTC: The unit comes with a PCF8563
LSB sizes corresponding to full scale real-time clock chip installed. There is an
readings accompanying CR1202 socket, but the unit
circuitcellar.com
does not ship with a battery (at least outside I also assumed that each of the units would
of China). The OS board support package perform as was described in the respective
integrates this RTC with the OS system time, user manual. However, the ones I received were
so the unit will m aintain the correct tim e sent by EDATEC's USA sales representative
even if power is removed and an internet and came with an older OS image installed
connection is not im m ediately available to and without the board support package
load the system clock using an NTP server. (BSP) installed. Later, I noticed that the CM4
This device is connected to the I 2 C-1 bus. Industrial's version number (internally labeled
The datasheet gives its 7-bit I 2 C address as on the PCB) was V I.3, not the latest V1.4.
0x51, which I confirm ed with the i2cdetect Note that, at startup, a new Raspberry Pi
utility. I tested it, and it was working fine, as will prom pt you to do an update. While this
described in section 4.6 of the user manual. is som ewhat of a lengthy process (depending
SPI NOR Flash: The CM4 Industrial on your Internet connection speed), it's not
comes with a 25Q32SCSIG 32Mb SPI NOR updating the installed Linux kernel to the
Flash device. This could be used to hold any newest version— it's just doing a lot of other
param eters that seldom change but need useful updates.
to survive a power-down, power-up cycle. When I contacted tech support at EDATEC,
Things like encryption and authentication the presence of the older firm w are was
strings come to mind. Section 4.10 of the user confirm ed. So I started from scratch and
manual covers this topic but is quite vague. downloaded the latest OS image from their
While I was able to follow the instructions website.
there and erase the SPI Flash, I was not able Loading a new OS image to the EDATEC
to mount it to the OS filesystem using the CM4 m odules is straightforw ard. You basically
com m and that they suggest: take the proper ZIP file obtained from EDATEC,
extract it, and use either the Raspberry Pi
sudo mount -t jffs2 /dev/mtdO /mnt Im ager program or balenaEtcher, both of
which are user-friendly. This is the procedure
I would need some help from EDATEC's to use if your EDATEC CM4 module has its OS
technical support to figure out how to use this located on a pSD card— which is how the CM4
Flash m em ory in Linux. Media unit that I received was configured.
However, the datasheet gives the pin However, it's more likely that a CM4
allocations for this device in section 4.1. Industrial module will be ordered with eMMC
Personally, it would likely be easier for me flash m em ory instead of a pSD card. In this
to utilize this Flash chip using Python and an case, it's a bit more involved.
appropriate library, given that the SPI port The CM4 Industrial (and other sim ilar
pins and CS line are known. modules with eMMC Flash) contains an internal
4G Modem: The CM4 Industrial's Mini Micro USB socket (labeled as A9 in Figure 3).
PCIe socket is meant to accept an optional This is a USB OTG port that is connected to
4G modem. This would be a Quectel modem: the BCM2711 MCU (via a USB switch device).
there are four different versions of this modem This USB port is configured to look like a USB
depending upon what part of the world you Flash drive when it is plugged into a PC. So,
are operating in. The custom Debian Buster OS when you do the flash operation from either
that I downloaded from EDATEC came with the the Raspberry Pi Im ager or balenaEtcher, you
Network Manager Tool installed (in place of the select this USB Flash drive as the destination.
standard dhcpcd network utility normally found There is one im portant thing to note.
on the Raspberry Pi OS). Section 4.5.11 of the If you plug the CM4 Industrial into your
user manual explains how to set up this modem. W indows PC (using a USB cable connected
EDATEC sent me the CM4 Sensing module to this Micro USB socket), and power up the
with a Quectel EC25-AFX modem (North Industrial, you will hear the standard tones
Am erica) installed. It would be easy for me to that indicate a USB device has been detected.
transfer this over to the CM4 Industrial. I have However, the W indows File Explorer will not
worked with cellular Particle loT modules, pop up to show you an attached USB Flash
but don't have any prior experience using a drive. This is unlike many 32-bit ARM MCUs
cellular modem with a Raspberry Pi. Also, I that run CircuitPython (as well as some other
didn't have a usable SIM card on hand. So, I ARM MCUs) which im m ediately show up as an
have not tried out this function yet. attached USB Flash drive.
Instead, before you plug in the CM4
CM4 INDUSTRIAL OS FIRMWARE Industrial, you have to load a custom Windows
When I received these modules from driver that is designed to recognize a Raspberry
EDATEC, I assumed that they came directly Pi CM4 module. This driver is loaded by a
from the factory in China, and that the pre- program called "rpiboot setup.exe"—the URL
loaded OS image would be the latest version. for which can be found in section 5.2 of the
24 CIRCUIT CELLAR • OCTOBER 2023 #399
dtparam = ant2
designing a microprocessor
can be easy.
Microprocessor Design Using
Okay, maybe not easy, but certainly Verilog HDL will provide you
with information about:
less complicated. Monte Dalrymple •Verilog HDL Review
«
real world.
Monte demonstrates
™»<>P>ocessor
how Verilog hardware
description language
(HDL) enables you to
depict, simulate, and
synthesize an electronic
design so you
can reduce your workload
and increase productivity.
CIRCUIT CELLAR • OC1OBER 2
DlOlDJ D
<
■ x*
FIGURE 1
Rear view of my bobblehead, left,
with a diagram representation on the
right. A current pulse in the copper
wire coil draws the magnet inwards
and rotates the rod. For a larger
response, another magnet can be
stacked on top of the first magnet.
advanced thin film solar cells as used in magnet being attracted into a coil of copper
rooftop systems have efficiencies above 25%, wire. The actuation was periodic with about
inexpensive polycrystalline photovoltaic cells a three-second cycle, and a capacitor was
available to hobbyists have efficiencies of used to store energy between activations to
about 10%-15%. ensure a strong response. A plan view of the
When I was searching for suitable pendulum can be seen in Figure 1. An acrylic
polycrystalline photovoltaic cells, the most plastic rod was used as the pendulum with
frequent comment I saw among customers the pivot point slightly above its center. The
was that the supplied currents claimed by pivot point can be adjusted to how much
manufacturers were far higher than what was wobble you want.
achieved in practice. At that point, I decided A low-friction rotational pivot with limited
to do a first-principles calculation of how motion in transverse directions is desired. I
much power should be obtained. Taking 10% made mine from a 4-40 bolt inserted into a
as the efficiency, and the theoretical optimum block of polyethylene, as shown in Figure 2.
insolation of l,000W/m2 , I calculated that I don't recommend lubrication, as oils will
a 5cm x 10cm 5V cell (about the largest gum with age. Dry graphite powder, as used
acceptable size for my project) would likely to lubricate locks, might be suitable, but I
give a maximum current of 100mA.
MECHANICS
I created the bobbleheads of my
grandchildren from Lego images I found on
the internet with image modification by the
GNU Image Manipulation Program (GIMP). For
the purposes of this article, I needed a public
domain image, so I selected the iconic image
of Apollo 11 astronaut Buzz Aldrin taken by
Neil A. Armstrong. I used GIMP to enhance
the image contrast and color saturation. The
image was pasted onto foam board and cut to
size with an X-ACTO knife.
A current of 100mA at 5V, 0.5W, was not
enough power for an up-down bobble action, FIGURE 2
as my experiments confirmed. However, it Detailed views of the pendulum pivot and attachment to the image head. The pivot should be low-friction
was enough for a side-to-side wobble action with easy rotation but limited-motion in other directions. This was accomplished by using a polyethylene
using a pendulum mechanism that I devised. block with a long path for the attachment bolt. Attachment to the image head was with a stiff wire that
The actuation was achieved with a rare earth allowed easy manipulation in all directions.
28 CIRCUIT CELLAR • OCTOBER 2023 #399
FIGURE 3
My simple coil winding jig (left), and
a detailed view of the coil assembly
with magnet and pendulum rod.
The counterweight, supplied by
multiple steel nuts, ensured that
S the resting state of the magnet was
E
R at the entrance of the coil. Careful
U
T measurement would center the
A
E carrier bolt for the magnet with the
F
lower portion of the coil opening.
However, in this case, I needed to use
a technique that my colleagues and I
humorously called "precision bending"
to effect the proper alignment. The
connecting wires from the coil are
sent to the bottom of the base, where
there's a cavity under the solar cell for
holding the printed circuit board.
COIL
The coil was 1,000 turns of AWG-36
enameled copper wire wound on a coil form
made from a 0.5" length of 0.75" outside
diameter PVC pipe commonly available at
home goods stores. Thin plastic discs were
glued to the ends of the PVC pipe section to
contain the wire. The large inner diameter of
the pipe allowed easy passage of the magnet
FIGURE 4 from one end to the other. The coil resistance
Bobblehead circuit. The circuit provides precaution against polarity reversal of the capacitors. The is slightly more than 100ft, and it varied
reverse-biased diode across the coil protects the drive transistor from an inductive kick-back voltage. from 103ft to 112ft for the five coils I made.
The circuit was designed with a 1500pF storage capacitor, which worked adequately. In the end, I used This resistance draws about 50mA from the
a 3300pF capacitor that slightly overflowed the circuit board edges (see Figure 5). nominal 5V source voltage; so, it's not too
demanding of the solar cell. The magnet
used is the commonly available NdFeB rare
earth disc magnet, 8mm in diameter by 3mm
thickness.
Manually winding 1,000 turns for a single
coil is possible, but tedious. Since I needed
to make several coils, I assembled a simple
winding jig from available scrap materials in
my workshop (Figure 3). The jig was mounted
in a bench vise, and the copper wire was
spooled from a vertical rod. While a manual
turns counter would be useful, a precise
number of turns is not required. I counted in
increments of 100, writing down when each
FIGURE 5
Printed circuit board layout (left), and a photograph of the board in the base cavity of the bubblehead
hundred's interval had passed as a memory
figure. As explained in the text, a 1500pF capacitor was originally used to store energy from the solar cell, aid.
but a 3300pF capacitor works somewhat better.
CIRCUITRY
The circuitry for the bobblehead, as shown
Additional materials from the author are available at:
in the schematic (Figure 4), is simple and
cheap. A CD4011B CMOS logic circuit is used
www.circuitcellar.com/article-materials
as a square wave oscillator and edge detector.
Reference [1] as marked in the article can be found there. While non-buffered CMOS logic ("A" series) is
seldom found today, it's important to use a
RESOURCES buffered ("B" series) chip. Circuit portions,
Texas Instruments | www.ti.com ICla-IClc, form a square wave generator, and
circuitcellar.com
FINAL COMMENTS
Children are not typically careful, and I
wanted to prevent any damage to the
ABOUT THE AUTHOR
bobblehead figures. For that reason, I
Dev Gualtieri received his Ph.D. in Solid State Science
enclosed the figures in transparent Lucite
and Technology from Syracuse University in 1974. He
plastic cases, 4x4x8" in dimension. I have
had a 30-year career in research and technology at
ceiling spotlights above my workbench, and
these have enough light to fully excite the a major aerospace company and is now retired. Dr.
bobblehead into action. LED desk lamps and Gualtieri writes a science and technology blog at
table lamps work when the solar cell is tikalon.com. He is the author of three science fiction
directly below them, as does an LED flashlight. novels, and books about science and mathematics.
Direct sunlight through a window will work See tikalonpress.com for details. You can reach Dev at
for a few hours a day; so, the bobblehead gualtieri@ieee.org.
would act as a sunlight intensity meter.
COIL INDUCTANCE AND MAGNETIC FIELD measurement is based on the resonance of a parallel LC
Inductance coils are the most perplexing components in circuit (Figure 7). Manually sweeping a signal generator to
electronic circuitry. It's possible to source many standard determine the resonance with a selected capacitor allows a
values of resistors and capacitors, but obtaining particular calculation of the inductance by the equation:
inductance values is a difficult task. That's why hobbyists 1
L=
are forced to wind inductance coils specific to their projects.
4tt 2F2C
There are some empirical formulas for winding coils
to a specific inductance value, the most notable being a for which L is the inductance in H, F is the frequency in
century-old formula for multilayer coils devised by Harold A. Hz, and C is the capacitance in F. For the bobblehead coil
Wheeler and published as "Simple inductance formulas for and a O.OlpF capacitor, the resonance frequency was
radio coils" in Proceedings of the IRE in 1908 [1]. Wheeler's 11kHz, giving an inductance of 20.9mH. You can see that
formula is as follows: Wheeler's estimate gives a smaller
value, the supposed reason being
0.8a 2N 2 that the bobblehead coil is longer
6a + 9b + 10c than Wheeler's model coil.
The magnetic field inside a coil is
where L is the inductance in pH, N is just a function of the current and the
the number of turns, a is the average turns per length:
radius of windings, b is the length
of the coil, and c is the difference D _ M -N
between the outer and inner radii
of the coil (all in inches). For our for which B is the magnetic field in
1,000-turn coil in the bobblehead, gauss (G), p0 is the permeability of
this calculation gives an inductance the vacuum (0.01257G-m/A), I is the
of 18.7mH. As Wheeler wrote in his current in amps, N is the number
paper, the equation is accurate only of turns, and L is the coil length in
for coils in which the three terms in meters. For the bobblehead coil,
the denominator are approximately this gives a field internal to the coil
equal. This would be a flatter coil than of about 50G for its 50mA current.
the bobblehead coil. The resultant attractive force of the
Most multimeters will measure FIGURE 7
coil to the rare earth magnet is a few
resistance and capacitance, but A circuit to measure the resonance of a parallel combination grams, somewhat less than the weight
not inductance. The technique that of inductance and capacitance. A capacitance of O.OlpF of a nickel coin. This underscores the
I've always used for inductance gave the resonance response shown for a bobblehead coil. need for a low-friction pivot.
es, sorry to say fellow engineers,
waded through, I'm not advocating for the
Y
the ancient saw is true. Size not return of through-hole components, 16-bit
only matters, but it's a critical multiplexed address/data buses, or discrete
acceptance parameter. I've done ICs with tenth-of-an-inch lead spacing
the research, conducted extensive, in-depth (Figure 1). It's just that as I continue to ripen
interviews, and can state here definitively that into juicy, soft, senior-EE-hood, my eyes aren't
the jury has returned their verdict: Smaller is what they used to be. As any regular reader of
better. But no matter what the size, it's also this space may already know, I'm somewhat
important what you can do with it. visually challenged, and ever since I can
Hold on a minute there! I can see that remember I've always been forced to wear
you're getting all excited but it's not what you corrective lenses to mitigate that condition.
think. Get your mind out of the flux gutter Technically my nearsightedness is so severe
and pay attention. This is not some random that I am legally blind in one eye. When you
post on Twitter, er, um, X. We're talking about can't see the big 'E' on the chart with your
embedded board size. And, as the red circles right hand covering your left eye, they hand
around your eyes from the magnifying lab you a cane, a tin cup, and some dark glasses
goggles you need just to place your scope at the ophthalmologist's office and send you
probe in the approximate location of the pin on your way. Though this condition can be an
on the ultra-fine pitch SMT part that your obstacle when you want to operate a motor
current embedded project is using can attest, vehicle or play a nice set of tennis, it comes
they're getting smaller by the day. in handy whenever I need to do an up-close
Now don't get me wrong—despite the inspection of some grain-of-sand-sized SMT
inordinately long run-on sentence you just component (Figure 2).
When tasked with identifying the
aforementioned sand grain, my optical
handicap suddenly becomes a super-power.
Fellow OG-EEs stare in frank admiration as I
whip off my Coke bottle lenses, bring the part
up right under my nose, and, using my uber-
myopic right eye to zoom in on the microscopic
font incised on the offending component,
read off the numbers. Of course, even 20/400
micro-vision isn't going to cut it when we
have folks like IBM creating chips with 2nm
FIGURE 1
(yes, that's 2 nanometers) transistor spacing
Olde-timey IC lead spacing (Figure 3), with the capability to place 50
circuitcellar.com 31
from Lantronix [6]. One of the most powerful Serving this trend, the company rose
market drivers of miniaturization in the last to become one of the premier providers of
few years has been the explosion of loT. wireless and wired networking devices. loT was
Consumers can't get enough low-power, high- a natural extension of this specialization. The
capability, extremely small-footprint devices. market drove its embedded devices towards
And Lantronix is at the forefront of companies even smaller form factors. As you can see in
in this space. Founded in 1989 in Irvine Figure 4, its line of wired and wireless loT
California, Lantronix was initially focused on devices is incredibly small. The board you see
networking peripherals— primarily network- pictured (Figure 5) has a full TCP/IP stack,
connected print servers. As networks moved embedded security profiles, AES 256 encryption,
into small and medium-sized enterprises, two RS232 serial ports, up to 16 GPIO pins,
Lantronix continued to innovate, making their and an integrated 10/100 ethernet PHY. Power
devices less expensive and easier to use and consumption for this configuration in operating
maintain—especially with the emergence of mode is typically less than 250mA. For those
home Wi-Fi networks in the 2000s. interested, Lantronix's eval kit package is
available as a download on Circuit Cellar's
Article Materials and Resources web page, as
well as a link to its developer kit guide [7].
NVIDIA: Another name in this space
is NVIDIA [8]. Known more broadly for its
graphics engines, NVIDIA is active in the
Artificial Intelligence (Al) sector as well. As
A l follows the loT out to the edges of the
network, the need for powerful, compact,
and power-efficient A l platforms only gets
stronger. Serving this market trend, NVIDIA
has developed the Jetson Nano, an Al-capable
embedded computing device that it says
FIGURE 4
Xpico versus George Washington
will "[open] new worlds of loT applications,
including entry-level Network Video Recorders
(NVRs), home robots, and intelligent gateways
with full analytics capabilities." In addition
to the Jetson Nano, NVIDIA has a full line of
miniaturized A l platforms, with the entry
level JetBot (Figure 6) aimed at the student/
hobbyist market. That said, the Nano is far
from just a toy. Leveraging Moore's and
Wright's laws, the Nano brings powerful
robotics processing power to the user at a
competitive price. See Circuit Cellar's Article
Materials and Resources web page for a video
that demonstrates how capable this platform is
[9]. And NVIDIA's hosted community platform
FIGURE 5 is chock-full of resources for everyone—from
Xpico Wi-Fi the beginner to the A l maven [10].
Toshiba: Next on my uber-small list is
Toshiba, which has jumped headlong into
the race for the smallest Bluetooth module.
Toshiba has a long history in semiconductor
components, microprocessors, Systems-on-
Integrated-Chips (SoICs), non-volatile data
storage, and much more. Bluetooth has
become an important modality for wireless
communications in the embedded board
space. With the ubiquity of this mode of
communication has come additional constraints
on bandwidth (maximizing the efficiency of
the band), along with the need for strong
error correction, dynamic configuration, and
minimal power consumption. Enter Bluetooth
• FIGURE 6 Low Energy (BLE) devices designed to meet
NVIDIA Nano JetBot the requirements for low-power environments
circuitcellar.com
the smallest BLE with the lowest possible World's Smallest BLE Device
IS IT IN YET?
All the above components, and many
others besides those mentioned, are just
the tip of the iceberg, so to speak. There
are many other companies leveraging these
minuscule components to give developers the
most flexible, and ultimately the smallest,
embedded platforms.
Espressif Systems: In that vein, we have
companies like Espressif Systems, with its
ESP32 line of embedded boards. The ESP32-
PICO [13] is one of a series of embedded
development platforms, designed with
the prototype builder in mind, that allows
a developer the freedom to design their
embedded application with confidence in the
tools and environment. The ESP supports
Wi-Fi, Bluetooth, and UART interfaces, has a
full USB interface for programming, and is
supported by multiple flavors of Linux and
other embedded OS like FreeRTOS. As you
can see in Figure 9, the board has an efficient
layout with lots of I/O and on-board memory.
Multiple frameworks are supported, including
Google loT Core, AWS loT, and Aliyun, to FIGURE 9
name a few. Espressif also provides its own ESP PICO development board
CIRCUIT CELLAR • OCTOBER 2023 #399
Resources
Adafruit | www.adafruit.com Nordic Semiconductor | www.nordicsemi.com
MIKROE | www.mikroe.com
circuitcellar.com 35
A B O U T THE AUTHOR
M ichael Lynes is an entrepreneur who has founded several startup ventures. He w as aw arded a BSEE
degree in Electrical Engineering from Stevens Institute of Technology and currently works as an embedded
software engineer. When not occupied with arcane engineering projects, he spends his tim e playing with his
three grandchildren, baking bread, w orking on ancient cars, backyard birdw atching, and taking am ateu r
photographs. He's also a prolific author with over th irty works in print. His latest series is the Cozy Crystal
Mysteries. Book one, M oonstones a n d M urder, is already in print, and book two is on its way. His latest
w orks include several collections of ghost stories, short w orks of general fiction, a collection called Angel
1
Stories, and another collection called Novem ber Tales, inspired by the fiction of Ray Bradbury. He currently lives w ith his wife
Margaret in the beautiful, secluded hills of Sussex County, New Jersey. You can contact him via em ail at m ikelyn es@ gm ail.com .
DATASHEET
N E S B n e M C
IR
E d a y n i n i C
U
X m a c
M Da
I
it e T
T o b r
o C
r- W le E
M n i re -e LL
A
d
E tsa
O -C a c R
e le •
N h
ll
a n h c O
C
M eh
T ie c t it t T
O
H f e o h ro B
E
S' , e R
ff 2
0
-m
rt
S te:
T e 2
o 3
O ri e #
u c S 3
P n 9
n h 9
IC a u A la b tr m b lo lo e o p tr M g a
se
l e u y
sc
x f o a
co s s
:
D
va
t,s
s,
a
n
so
n
te M
e
r
g
e
r
le
e
v
e ic
ro
e e
d co
w
-
b
a
la p
w
o m
tr
e re
p
u
la
M
E
n
sf
o
E
M
S
n
u
m
l
T in e
e
n
n
ic
e
C a rs ch a "s
e l w e a M , a n
- b ly n n sc ra y le isg ts e s ri S rm se th , l
D to o w a g st n in r ly o ty w te S m h h
ro ze
lo h le e e trc o f n n e ta e
so
is i
C a g d m o h t r m co se s. fo y so ' ch
y m s i s
d it a g ile
.s n n n
te o ve n
ch e m g te
C e y , e a r ch u r o
in a a h c
o r to th to s.
"
ic y m n su si P r g n o r
o
e h s, a u m ti se n n p cu lo i o n e y l h
n n m r a lik a A a c v ri n o e ro g f th n
v e s e n p n
ss fa
p e m lo x d
ra
y a
ca
, n
tw a d
ch
d . a
si
n g t te t l th a n i o
e ke a a ie ro -p
u
ct ti
o T g y u is e w
o re
n v d b h p d . lo
rs
rt d
ta v y e o u e ro ri n e
irly
a r
ct e th sy e te
e
rk o f d n . , o s a e la ' g
e f lu d ci u g A y p co je ss tse re g y
o ro e e co n
re
— n a p n h t se e m
te r
rs f ics m ti m g a ce
d ls M ct l n e a
io o b si u d d w o E
ilc ti . a e ti fo
s
st
x
S in
n n e g o h M a n t a re h
e te iz d n sre u
ily
d E h M ti u ct
l in
ci te
a
n ,s
th e d s , ic M a S o e o c io fr (M te d
d lli e d e
tc in e h n s n to o d s
g a d n o v S ve
s u m n E m
re e n w o th m e t ic m ld o t M d
la n d o h t e g e te a se fo to f a S ic to e r
t o p ir e e c n n n n ) e
e ce
lrd w te
o s ra s. a h e s r p y o ro b s
d co ch n s o a g o in f v
p sy n w n
ss si th te F s is p te e se -e ri
n
ig
o
r n a e o ze a d u a h e
rs v ro
n n
so
n le g n
o st e ro ib
t a w e lu se lu
d e u lo le w trh v ig ci r w n so ct
u m
ct
n u g a c a it e e h a a ie ita ito s ro yo s t
tc s to d se a n re h ry ly lly re yt i
n lly e n o rs
u o io
a
y,
t r, r r . - lu
n .s n
n i
o In ti z
u in o t to o m o h in a te th b im o m d e a m to o e
n f in f r n
sh
e
lim th e x n n
ce sp fe i d M u ig te d ch a i
p e a
f-
T e is a
d d
m e a lt e h W n n g h d it T isve rk e s
ir ri E ip n rf w , k s ic l
e h lo ti
n e n .
e a n st y.
M v
-p h a s a u in in a e st
t a s
n ti g N S le ir re e e th n e g l p g a b W
ts o o th icn a e i
n d
se . s a
ss, e n rt le e
n
s. (
p e ty n ci
e g d a r o e n
to u
se
p m
ra
ri p e A p p a ic -u p n
in
ce
n e
si
o r w b a v e s p fr
o p lr h p p e s
e N n s e n el u e x II(
m e e o w ro o
d e sa so s n it rt n te a o lic lci a o
s,
it th v r o t a p h ,s se n T a a d u
rt u
o n p a
rs
e e in ri f a re
m
to sp
— ) ti e y n
s
so n
r@ rt t ly o s l cc
s o a si e o n
ti
o ti
o
fo h e , p e e o p h c v x v n n o n
it
w
lu d
ci e n t n se le su e a th
e e a ir te s n ie ti a
rc ll
o d th io s n r ti
o n s e ly m ,s s e
s o u n
u w
le e n o ro e n in e p
tu rt th ll n
it is s si m . g s sh x in le a to a e
fo
a p d
in )
s,s d rs n p p ll n i fo r s
fo s.
ce
g co a , g e re ri lo a : y th m r m th r T
lla v te se u a n r u a e a a h
g lu a th
u n p k a a e e n e
r. a I sl m l
ia e n d in to cc
n in n M rk e x
is
co vi s,r so a
ti
o m e E e m o
m
lle n b re it
s g n y d t,
M is
v m
h re
o le 's th rs
w to
. o le w u tp b e
ti e
yr p r e , h b h tr S la e r n a
. e o e a th r isz M ro
e tsr a c d a g n
p to
h a m g o sm e o lie m r n e d b s
f re d u t a le r e e ia e u
s g y a o e ,s l sp se
to d n n
y a
o e e l ro w f te y o n d
co
u
u v v e in rt
s e r ro o
In s d a m
a n e w te
se sc o p e b rs
u
rt o a sy
n p m
ts lo g n o h n
ce
o
te a y. a e
ila p e so p lrd o n h rn ti sr st
e ce
n
fi b e a ra e n si ti a c e o m i
ro
n l th lt t rs o e n tl cs v a n u
d e e rs h e , s,
f s g y, , e n t- , is s o se
f s
circuitcellar.com 37
DATASHEET URLS:
Datasheet:
MEMS Sensors
DATASHEET URLS:
dusty applications with the possibility drivers can deliver up to 10 differential learning core (MLC) with adaptive self
of water spray, condensation, or or 20 LVCMOS low-jitter clock outputs. configuration (ASC). The FSM and MLC
immersion. The small LGA assembly This ClkSoC supports four additional with ASC deliver outstanding always-
consists of a gas sense element and a clock inputs with fracN dividers, on, edge processing capabilities to
CMOS signal conditioning IC. The sense enabling virtually any input to output the LIS2DUX12. The LIS2DUX12 MIPI
element is a Si-based microhotplate frequency translation configurations I3C slave interface and embedded
with a robust and highly sensitive from 8kHz to 2.1GHz. 128-level FIFO buffer complete a set of
metal oxide (MOx) chemiresistor. The features that make this accelerometer
signal conditioner (ASIC) controls the • Quad fractional-N PLLs with a reference in terms of system
sensor temperatures and measures integrated VCO and loop filter, 120fs integration from a standpoint of the
the MOx conductivity, which is a typical RMS integrated phase jitter bill of materials, processing, or power
function of the gas concentration. The • Wide output frequency support: consumption.
measurement results are easily read Differential outputs from 8kHz to
via an PC interface with the user's 2.1GHz; LVCMOS outputs from 8kHz • Supply voltage range from 1.62V to
microprocessor, which processes the to 250MHz; Supports 1Hz to 2.1GHz 3.6V
data. output frequency on one output • Four operating power modes
• Wide input frequency support: • Ultralow power consumption
• Sensor output based on A l machine Differential input from 8kHz to • Low noise down to 220 pg/VHz
learning algorithmic 750MHz; LVCMOS input from 8kHz to • ±2g/±4g/±8g/±16g programmable
• High sensitivity to hydrogen based on 250MHz full-scale
resistance output • Individually configurable output • ODR from 1.6Hz to 800Hz
• Heater driver and regulation loop for formats and VDD supply: LVPECL, • Embedded machine learning core
constant resistance, minimizing effect CML, HCSL, LVDS or LVCMOS; 1.8V, • Programmable finite state machine
of environmental temperature on 2.5V or 3.3V • Adaptive self-configuration (ASC)
signal • Flexible input to output frequency based on the sensor processing
• Built-in NVM for module-specific data translation with jitter attenuation, output (FSM / MLC)
(configuration and calibration) four inputs, 10 outputs • Embedded temperature sensor
• Ultra-low average power consumption • Programmable jitter attenuation
down to 160 pW bandwidth for each PLL: ImHz to STMicroelectronics
Renesas 4kHz www.st.com
www.renesas.com SiTime
www.sitime.com
DATASHEET URLS:
n 1973, there was a movie called waypoint (a geographical position with specific
I
Westworld, about a robotic amusement latitude and longitude coordinates), where I
park. The movie trailer said, "Nothing parked the car.
can possibly go wrong. Go wrong. Go I had not been to Brainard before, so I was
wrong..." Of course, the entire movie wasplanning a short familiarization hike, maybe
about things going murderously wrong. an hour or so. The only other people I saw
My article will be unusual, in that there are all afternoon were some cross-country skiers,
no schematics, and there is no code on the and they were long gone by the time I got my
Circuit Cellar website. It is about what happens snowshoes on. I've never had a good sense
when technology goes wrong, and how we of direction, so when I decided I'd gone far
can prevent or deal with such situations in enough, I wasn't sure of the direction to the
our designs. I'll start with a short version of car. I should have backtracked on the trail
my own potentially deadly experience with and returned that way. But it was late, so I
technology that went wrong. decided to bushwhack to the car in a straight
line using the GPS. But the GPS waypoint was
MY ACCIDENTAL CAMPING TRIP bad, and it led me in the wrong direction.
I live in Colorado. In March of 2015,1 went By the time I reached the waypoint and
snowshoeing at an area called Brainard Lake, realized I was lost, the shadows were getting
which is at about 10,000 feet altitude. I had long, it was getting cold, and I had put back
planned to go to a different area early in the on the layers of clothing I had taken off. I
day, but it was inaccessible due to snow. So I considered hiking back, but the area I'd hiked
went to Brainard in the afternoon. I set a GPS was all trees and deep snow—difficult terrain,
circuitcellar.com
and no place to stop if I ran out of daylight. because it would have taken me right back to
The place where I ended up had a tree with my car. That GPS model isn't supposed to set
dry ground, surrounded by elk droppings. a waypoint if it doesn't have a good fix on the
Presumably some elk had recently spent the GPS satellites. But this one time, it did, without
night there and melted the snow. I decided it reporting any error or warning.
was safest to stay there. I worked on GPS development back when
It was nearly dark, and I spent the little it was an all-Department-of-Defense (DoD)
time I had tearing down pine branches for program, so I have some knowledge of how
insulation and collecting firewood. It got very it works. The GPS system is very reliable;
dark—trees were just vague shapes. I built a what it does is technically complicated,
fire but didn't have enough wood to keep it but conceptually very simple. But the GPS
burning through the night. (If you've never receivers we use are not always as reliable.
done it, you'd be surprised how much wood I contacted the m anufacturer to see if there
that takes.) Figure 1 is a picture of the fire was a firm ware update for my unit, but never
as I was getting it started, you can see my received a response.
water bottle packed with snow for melting. In my case, the GPS didn't tell me (or
My gloves were wet, so I took them off. They didn't know) that the waypoint was bad.
froze solid overnight. Fortunately, even with my mistakes and the
I didn't have cell phone signal, and I faulty GPS indication, it ended well enough.
couldn't even send a text message. (Safety But there was another situation where a
tip: a text only needs a brief connection to faulty indicator caused a nuclear meltdown.
transm it, and will often be sent even if the
connection isn't stable enough for a voice SENSOR FAILURE: REACTOR
call.) I decided that since I was well away from MELTDOWN AT THREE MILE
where I should have been, searchers might ISLAND
not look there for a while (later confirmed The Three Mile Island (TMI) nuclear reactor
by one of the rescue searchers). So, despite was completed in 1978. In 1979 it suffered a
the usual advice to stay put, I decided to partial meltdown of one reactor (Figure 2).
follow my tracks back in the morning. If The Nuclear Regulatory Agency identified
snow covered my tracks during the night, I'd several causes of the incident, including
follow the bad GPS heading backward until I inadequate operator training and incorrect
intersected the trail, and as a last resort, I'd procedures. There are a number of articles
follow my compass. about TMI, including one on Wikipedia [1]. I
I started back about a half hour before won't go into all the details; rather, I want to
daybreak with my headlamp. By the time I look at one small piece of the problem. One
reached the more difficult terrain, there was thing stood out to me, that, like my wayward
enough sunlight to see. Searchers had a GPS, could have mitigated the entire scenario.
helicopter looking for me. I could see them, In the TMI reactor, a relief valve was stuck
but they couldn't see me, because I was in a open. However, the valve had a light indicating
wooded area. that it was closed. But the light actually
I eventually encountered one of the dog
search teams and we returned to the trailhead.
One of the rescuers said they had done rescue
searches in conditions less severe than mine
and the outcome wasn't good. The sheriff's
report said I became disoriented, found a dry
place to spend the night, constructed a shelter,
and built a fire. "Shelter" is a bit of a stretch;
it sounds like I built a log cabin or something.
I know what I did that got me lost. I
started out late, leaving me no time to recover
if something went wrong, I got off-trail in an
unfam iliar area, and I followed the GPS into
difficult terrain. One of the rescue searchers,
who was on cross-country skis, said she was
impressed with some of the terrain I covered;
I told my wife later that I had no intention of
covering any terrain that would impress those
people.
I admit that I had made some bad decisions. FIGURE 2
But if the GPS waypoint had been correct, none Newsmen and spectators stand in front of the main gate of the Three Mile Island Nuclear Generating
of my bad decisions would have mattered, Station in Middletown, Penn., April 2, 1979.(Photo Credit Jack Kanthal/The Associated Press)
CIRCUIT CELLAR • OCTOBER 2023 #399
indicated only whether power was applied monitor and a temperature sensor. What if you
to the solenoid that controlled the valve, not have a stepper motor or solenoid, like Three
the actual valve position. The operators took Mile Island, that your software controls but
several actions in the first few hours of the has no way to check? How bad can things get
accident, based on their assumption that the if the solenoid coil burns open or the solenoid
valve was closed. Those actions made the gets stuck and can't move? Can two parts
problem worse, and likely turned an orderly smash into each other if the stepper position
shutdown into a disaster. isn't where the m icrocontroller (MCU) tried to
I'm not a nuclear engineer, and the plant send it? Can a cascade failure occur like the
was built in 1978, without a lot of our modern one that happened at Three Mile Island? If
technology, so maybe it wasn't feasible to your stepper can actually break something, it
detect the actual valve position. But like my GPS probably needs an encoder to verify position.
that was sending me the wrong way without Do you need a way to verify that a solenoid
warning, there was no way for the operators is in the right position or that a heater is on
to know that the valve was actually stuck open. when it should be—or off when it shouldn't?
Like my accidental camping trip, a lot of Ideally, sensors should be designed so that
things went wrong at Three Mile Island— they never saturate in normal operation. For
mostly bad decisions—but the effect was example, in a piece of equipment designed
multiplied by the bad information about to operate up to 50°C, and using an 8-bit
the position of that one valve. After reading analog-to-digital converter (ADC) to measure
articles about that incident, it appears to me the temperature, don't make OxFF equivalent
that if the valve light had reported the actual to 50°C. Instead, scale the ADC input so
position of the valve, the operators would have OxFF is the value for, say, 70°C. That way,
taken the correct actions instead of the wrong if you ever see OxFF, you know two things:
ones. There would still have been a reactor the temperature is way out of range, and
accident and a shutdown, but probably not a the sensor reading can't be trusted because
partial meltdown. it's saturated. It might be 70°C or it might
Failure o f Sensors in Embedded Systems: be 150°C; you just don't know. But you know
In an embedded system, a small thing can something needs to be done, whether it's
sometimes lead to big issues. The Boeing 737 a system shutdown or notifying a human
MAX experienced two fatal crashes, because operator. And if that temperature sensor ever
a sensor sent faulty information to the flight does read OxFF, don't display 70°C for the
control system, indicating that the plane's nose operator, display "Overtem p" or something
was too high. In the two crashes, 346 people similar. Because, again, you can't know the
died. The plane was taken out of production actual value of a saturated sensor.
until the problem was solved, and the entire If using a pressure sensor, can you detect
incident cost Boeing billions of dollars. an overpressure failure? And what can break
How could such failures be prevented? In if the pressure can't be measured?
designing an embedded system, ask yourself In some cases, where there are potential
what happens if a sensor goes bad. Can you safety issues or equipment damage, a
detect it? Depending on the design, an open redundant sensor is a good solution. Yes, that
or shorted sensor might be easy to detect. adds cost, but the cost of a single field failure
But a faulty sensor might not. Do you have a may exceed the additional product cost many
way to detect that a sensor is sending bad or times over.
noisy data? Can you detect an out-of-range Think of the Boeing 737 MAX as an
condition? And if you can't detect it, what is example. The plane actually had a redundant
the worst that can happen? sensor, but didn't use it. I don't know the
Answering that last question may require a technical challenges involved in integrating
detailed analysis, or even simulating a faulty part. the second sensor, and there was reportedly
I used to keep a flakey cable in my desk just for a desire to minimize the need for additional
that kind of testing. You may not be working on pilot training for the new version, but it's
anything that can cause deaths, but something hard to imagine that the cost would exceed
like an industrial robot can do a lot of damage if the human and monetary cost of those two
things go really wrong. Even something like the crashes. Even if you can't tell which sensor is
temperature control in a soldering iron can do working, getting wildly different results from
damage if it runs wide open. redundant sensors is a signal that something
It's easy to fall into the trap of designing is wrong and human intervention is needed.
things to work when nothing is broken, but A lot of industries use some version of
how badly can things go sideways if a sensor failure mode effects analysis (FMEA) [2],
or something else breaks? Will the system which attem pts to determine what happens
catch fire if an essential cooling fan fails? If when things fail, and the potential severity of
so, you should probably have both a fan speed the failure. Even with systems that are not
circuitcellar.com 43
safety-related, thinking about these situations was too slow, it was that the machine setup,
and handling them in your design will make it being motor driven, took seconds to complete.
more robust. A reputation for poor reliability The software design assumed the setup would
may not kill anyone, but it can kill a company. be complete before the operator could change
modes. It was a genuine race condition but the
FAULTY SOFTWARE AND error window was several seconds wide.
DESIGN: RADIATION THERAPY In your system, it might not be a human
OVERDOSING BY THERAC-25 operator; it could be an input from some
The Therac-25 was a radiation therapy external device, such as a speed sensor,
machine used for treating cancer. Produced USB interrupt, or some other event. Can an
in 1982, it was controlled by a PDP-11 unexpected combination of events put your
minicomputer. The Therac-25 had two modes system into an unknown state? And can you
of operation, one where a low-power beam detect it when that happens? What about an
was used to target a specific location on the intermittent connection that produces runaway
body, and another mode where a much higher pulses much faster than the design can handle?
power was used with an attenuator to produce Problem 2—Inappropriate Code Reuse:
attenuated x-rays; (I'm sim plifying this a lot). The Therac-25 used code from earlier versions
Over the course of 2 years, the Therac-25 of the product. But the earlier versions had
was involved in at least six incidents involving fuses and interlocks to prevent the machine
overdosing patients with excessive radiation, from applying high power without the
causing at least three deaths. There are attenuator. The developers of the Therac-25
numerous articles about the Therac-25, both used the old code, but removed the hardware
on the Internet and in print publications, so interlocks, trusting their software skills to
I won't rehash the details here. They are prevent dangerous conditions.
C
summarized in a Wikipedia article [3]. In an old song, "Signs," the singer reacted O
L
In the Therac-25, the operator would select to a "No trespassing" sign by shouting at a U
M
the treatm ent mode, and the PDP-11 would farmhouse that they didn't have the right to put N
S
set the beam power and rotate a turntable to up a fence to keep him out. There is an old saying
put the attenuator between the em itter and that you should never tear down a fence until
the patient. The problem occurred when an you understand why it was put up. That fence
operator would start the setup for one mode, might be there not to keep you out, but to keep
then switch to the other mode. The machine in an aggressive bull. The Therac-25 developers
took several seconds to set up the hardware, removed the interlocks that prevented exactly
and the computer would leave the machine the kind of dangerous conditions that caused
partially configured when the mode was the incidents. The software bugs had existed in
switched in mid-setup. The high-power beam the earlier machine, but the hardware interlocks
would then be applied to the patient without prevented harmful incidents.
the attenuator, causing severe radiation burns. Code reuse isn't a bad thing. But when
Numerous faults were found in the reusing code, especially on new hardware, it
software and in the design process. I want to is im portant to analyze what can go wrong in
look at just two of the design flaws and their
applicability to our embedded systems. To Ceiling To Ceiling
Problem 1—Software Design and
Operator Error: When asked why it's hard to
design a bear-proof garbage can, a Yosemite
park ranger supposedly said that there is
considerable overlap in intelligence between
the sm artest bears and the dumbest tourist.
It's not that bears are sm arter than people,
but if someone can use a bear-proof garbage
can incorrectly, someone eventually will.
The Therac-25 engineers attempted to
reproduce the failure. But the problem was
actually caused by quick operators combined
with bad software. Operators of equipment like
that use it all day, every day, and they have a
lot of opportunity to get very fast at routine
operations. What happens to your system
if the operator performs some unexpected
operation? Does it recover or is it in a bad state? FIGURE 2
The Therac-25 race condition was caused by a Construction design change at the Kansas City Hyatt Regency Hotel. This change led to the collapse
fast operator. But it wasn't that the computer of two overhead walkways, and hundreds of fatalities and injuries.
CIRCUIT CELLAR • OCTOBER 2023 #399
the new system that didn't apply to the old none of the others were fatal.
one. I can't read the minds of the developers In the case of the Hyatt disaster, the
of the Therac-25, but I am confident that problem was that nobody recalculated the
if there were interlocks to prevent beam stress analysis for the design change; possibly
activation in the dangerous configuration, the original designer didn't even know the
those patients wouldn't have been killed. The change request had been made.
developers of the Therac-25 had confidence in This goes back to the adage about tearing
their software skills and in the applicability down a fence before you understand its
of the reused code to the new h a rd w a re - purpose. Apparently nobody in the decision
overconfidence, as it turned out. chain for that change even recognized the
Some solenoids, heaters, and other parts problem or tried to check. In a building like
aren't designed for continuous operation and that Hyatt, there are thousands of bolts,
will burn out if powered continuously; such tons of concrete that must be poured to
a device controlled by software can fail if specification, miles of electrical wiring, and
left energized too long. If your software can hundreds of electrical fixtures. After an
do actual damage to the hardware or to the incident investigation, when the cause of
user, how well protected is it against such the failure has been found, it's easy to say
conditions, and how confident are you that the someone should have checked; hindsight
protections hold up against a "dumb tourist" always has 20/20 vision. But every design
who will try things you didn't think of? change can't result in a complete reanalysis
of the entire building—how would someone
FAULTY DESIGN: WALKWAY know to check the stress on that specific nut?
COLLAPSE AT THE HYATT If your embedded system hardware or
REGENCY HOTEL software has a safety-critical element, how
In 1981, two overhead walkways in the does anybody know it's important? You could
Kansas City Hyatt Regency Hotel collapsed, add a comment to the code: "Safety is s u e -
killing 114 people and injuring 126 more. As do not change without analyzing 'xyz'." But is
with the other catastrophes mentioned here, that adequate?
there were extensive investigations into the In a similar way, how are safety features or
causes, which are summarized in Wikipedia limitations that prevent device damage retained
[4]. I want to focus on just one thing that went in your code or in the hardware documentation?
wrong, and how it is applicable to our designs. As I mentioned, some solenoids will burn out
The two overhead walkways were tied to if current is applied too long. Does your code
ceiling supports, and then held up with hanger have fail-safes to prevent these events? How
rods that went through the walkway beams. do you keep someone from changing them?
During construction, a request was made to Someone changing the code years after original
change the design to make fabrication easier. development may not even be aware of the duty
In the original design (Figure 3, left), a cycle limitation on the solenoid.
single support rod goes through the upper My Experiences with Faulty Design
beam, which is held by a nut. The rod Changes: I worked on a project years ago
continues to the lower beam and is held by that involved a rotating drum. Someone
another nut. Thus, the rod carries the weight changed the drum material, presumably
of both walkways but each nut carries the to reduce cost. But the original drum was
weight of only one walkway. made of conductive plastic, whereas the new
In the modified design (Figure 3, right), one was ordinary plastic. The result was an
there are two hanger rods. One rod stops at unintentional Van de Graaff generator that
the bottom of the upper beam and another could produce arcs up to a quarter inch lo n g -
rod connects the upper and lower beams. As right into the control PCB. Nobody was hurt,
a result, the nut on the upper beam, and the but the hardware sure didn't like it. How did
beam itself, have to support the weight of that person make that decision?
both walkways instead of just one. It was not I worked on another system where
designed to do that. guys in another group, in another country,
The design change request was not had difficulty getting a part. Their vendor
unreasonable from the viewpoint of the recommended a replacement, and they
company making those support rods. In a accepted it without asking me, though I had
complex building like that, there were probably designed the PCBA and firmware. The boards
many design changes during construction. But seemed to work, but we got a lot of failures
in the field. Nobody was hurt, but a bunch of
Additional materials from the author are available at: boards had to be replaced in the field, and
www.circuitcellar.com/article-materials erroneous results from those boards cost the
References [1] to [4] as marked in the article can be found there. company money. The alternate part worked
well enough to pass board-level test, but
circuitcellar.com 45
didn't work over the full range of conditions occurrences, and standards have been created
encountered in the field. to accommodate those lessons. Hazard and
When I looked into it, it was obvious operability (HAZOP) analysis has been around
what had happened. The replacement part, since the 1960s, and use of FMEA started in the
a current-sensing resistor, was the right size 1940s with the U.S. military. Yet, the Boeing 737
and type, but the wrong value. I had put notes MAX crashes happened despite all the lessons
on the schematic that included the calculation learned from earlier disasters, and with all
for the part, and those notes should have those new processes and standards in place.
made it obvious not to change the value. I'm No m atter how many lessons we learn and
guessing that the engineer who approved the standards we create, humans are a critical
change didn't even look at the schematic. link in the development process. With the
Thus, in an exact parallel to the Hyatt disaster, complexity of modern systems, knowing how
an engineer trusted the recommendation of one failure affects the entire system isn't
the vendor without checking with the designer always obvious. The im portant point is to
(me) or the documentation. The Hyatt disaster make sure you understand how things can go
happened essentially because an obscure but wrong and how badly they can go wrong, and
potentially hazardous part of the design was to design with that in mind.
changed with no review or accountability. Hopefully, this has given you some ideas of
Could something like that happen in what to look for in your own designs—so you
your designs? How does anyone in your can avoid having your or your company's name
organization know to evaluate such a change, in the press after some high-profile disaster
and who has the authority to require that happens! Because things do go wrong. Go
such an analysis be performed? wrong. Go wrong...
C
CONCLUSION O
L
There have been many incidents and U
ABOUT THE AUTHOR M
disasters that we can learn from. I've only Stuart Ball recently retired from a 40+ year career as an electrical engineer
N
S
looked at a few here, and these are relatively
and engineering manager. His most recent position was as a Principal
notorious in the engineering world. Many
Engineer at Seagate Technologies.
safety lessons have been gleaned from those
A V NET
in Thin S lices
How This-Slicing
Can Help’ Us
The Search mor "Fists
jfijilBWbddded Systems
J
L
O
C
f
By
Bob Japenga
FIGURE 1
Blink: The Power of Thinking Without Thinking, by Malcolm Gladwell
number of years ago, I was part "thin slices" (from which the column gets its
of a leadership team wrestling name). So, let's start there.
with some long-term planning
decisions. We were considering WHAT DOES THE TERM "THIN
a major shift in one of our activities. I had SLICES" MEAN?
proposed that we do some more study and First, some background. In Malcolm
reflection on the viability of the change. One of Gladwell's bestseller Blink (Figure 1), he
my teammates was incensed. "We have got to talks about the way we make decisions.
make a decision and get moving on this right In particular, he describes a process our
now. Another study will bury the project." brains go through called "thin-slicing." Thin-
I share this story to let you know that, in slicing describes our ability to find out what
general, I err on overthinking a problem. I is important with limited data. I have been
am a process-oriented guy who likes to work designing embedded systems for 50 years,
through all of the details before I launch on yet I find I am always a beginner. I always
a new endeavor. I like our systems and our have limited data and a limited vision of what
processes to be ever-improving. is coming next. The field is so broad, and the
I share this anecdote because this month applications so varied, that no one person can
I would like to build a case for (sometimes) completely understand even a small portion
making embedded system design decisions in of the field.
the blink of an eye. In the process of doing Let's look at some details from the book: In
that, I also want to celebrate the beginning of his first chapter, Gladwell focuses on explaining
13 years with Circuit Cellar as a columnist. As how thin-slicing, or rapid cognition, works in
some of you know, I end every column with everyday life while making decisions. Gladwell
something like: "Next time we will wrap up states that, often, a little information about a
this series and look at specific strategies that person or situation is enough to make correct
I have found helpful in debugging embedded conclusions. He describes an experiment
systems. But, of course, only in thin slices." where friends and strangers were asked to
Many of you weren't with us when I started evaluate a student's personality (with respect
these columns and explained what I mean by to extraversion, agreeableness, emotional
circuitcellar.com 47
SUMMARY
Let me restate my hypothesis. We can
create fists, or signatures, to aid in embedded
systems design and debugging. Malcolm
Gladwell demonstrates in Blink that we can
solve complex problems quicker than expected
(Figure 4). I've only scratched the surface. I
would love to hear from you. Can you provide
some other fists to help us get to the bottom
of a problem more quickly? Perhaps you can
augment the areas in embedded systems
design for which I've proposed to create
fists. More critically, can we get some serious
research in developing fists to help speed up
the various aspects of our work? I think it's
possible. Is there some PhD candidate looking
C
for such a project? We certainly need it. O
L
Next time, I want to explore requirements U
M
elicitation. How do we obtain the N
S
requirements for a project? But of course, FIGURE 4
only in thin slices. Blink - solve complex problems quicker
Re n e s a s
50 CIRC1OTWELLAR • OCTOBER 2023i
From th e B<
UsMRnm!Ss8ElBB8ES8
Partl2^Moa mnW l imt:-
flu ■M l
rA
S
N
S energy system I built for lighting my Scout troop's large ■
storage shed. I described the battery I chose, and the
I Modbus protocol with RS-485 serial communication used for
remote monitoring of the system's performance ("sniffing"
M
U
L or listening to communication on the bus, and decoding
O
C
each message). This month I expand on this node's capacity FIGURE 1
Two south-facing 100W solar panels are mounted
to do much more than just listen and decode. on the back of our Eagle's Nest equipment shed.
By
J eff Bach iochi
hanks to a grant from the Hartford battery node (yes, this is a smart battery)
T
Foundation for Public Giving, our through a twisted-wire RS-485 network, using
newly constructed equipment shed, the Modbus protocol. So far, our solar supplier
the Eagle's Nest, now has a system is not publishing the Modbus specifications for
each node. This makes it a bit difficult to add
to collect and store solar energy, and then
use it to power LED lighting throughout our own node to the bus.
the shed's two floors. The system uses two Fortunately, the Modbus protocol is an open
south-facing solar panels, a solar charge standard, with specifications available from
controller, a lithium iron phosphate battery, Modbus [1]. With them, we can understand
and a Bluetooth module (Figure 1, Figure 2, the communications protocol. In my project
and Figure 3). Previously, the Scouts used the last month ("Local Isolation: Using the Sun's
flashlights on their cell phones to search for Energy," Circuit Cellar 398, September 2023)
and pack equipment needed for meetings and [2], I created an RS-485 node that can listen
campouts. This caused safety issues that were to ("sniff") all the communication happening
eliminated by providing sufficient permanent on the twisted pair bus, and decode each
lighting. message. This month I will expand on this
We can light the area with simple 12V LED node's responsibilities to do more than just
lighting bars, so we won't need to convert listen.
the energy into 120VAC; a low voltage (12V)
system will suffice and will be safer. It can MODBUS REVIEW
all be monitored with a cell phone app that The Modbus protocol uses two types of
allows you to see real-time and historical data, nodes: clients and servers. In our case, the
as long as you're within range of the shed. Bluetooth node is a client, and the controller
Unfortunately, it is too far from our sponsor's and battery are servers. The protocol requires
building for power or an Internet connection, a client to request data from a server. Servers
so we're on our own. The Bluetooth module have address registers where data is kept.
communicates to the controller node and These are defined as input registers, holding
circuitcellar.com
are the server address and the command. The remaining data
and CRC bytes are in pairs or words.
don't have to add much code to allow the sniffer to become
BLUETOOTH CLIENT a client. Most of the code allows the serial port to become
All communication is initiated by the client. Here, the client a user interface. This is presented as a menu of supported
is a Bluetooth (BT) module. The client receives commands from commands.
the cell phone application (DC Home). To know which nodes
(servers) are in a system, you must first select the BT module. 1 - Read a Register
When communication is established between the application 2 - Write a Register
and the BT module, you can add devices by connecting them 3 - Restore Factory Default
one at a time to the Modbus. The application will perform a 4 - Clear History
request for register OxlA to the general broadcast address 5 - Change Address
0x00. 6 - Change myDebug
0x00 0x03 0x00 OxlA 0x00 0x01 Ox?? Ox?? Note that the first two menu items allow for register reading
server command register register count CRC and writing. The second two items are system commands and
are not used in normal querying. The last two items change
The connected server will respond with a packet. application parameters, the server address, and the kind of
debug data that is sent to the serial port. In activity on the Modbus that we should sniff
most cases, we will be using item #5 to select (attend to). For this application, we add a poll
the server we want to talk to, and item #1 to to the primary serial port (USB), i f ( S e r i a l .
query information. Let's spend some time on a v a l 1a b le ( )). On the primary port, we are
item #1, "Read a Register." using the Serial Monitor in the Arduino IDE to
handle the user I/O. Because debug data also
QUERYING INFORMATION uses this port, it is best to keep the debug
In the application described last month data to a minimum. Note that you can see
[2], the auxiliary serial port, i f ( S e r i a l l . which bits enable and disable various debug
a v a i 1a bl e ()), was polled to see if there was output in the sketch listing. Since we are
11
/ / s t a r t lo o p
//
v o id lo o p ( )
case 1:
S e r i a l . p r i n t l n ( “ Request a R e g is t e r ” );
S w h i1e ( S e r i a l . a v a l 1a b l e ( ))
N
M
U
L S e ri a l . re a d ();
O
C
S e r i a l . p r i n t l n ( “ How many r e g is t e r s do you w ish to re a d ? ” );
S e r i a l . s e tT im e o u t( 10000);
m o d b u sR e g iste rC o u n t = S e r i a l . p a r s e l n t ( );
S e ri a l . p r i n t l n ( “ You asked f o r “ + S trin g (m o d b u sR e g iste rC o u n t) + “ R e g is t e r ( s ) ” ) ;
S e r i a l . p r i n t l n ( “ E n te r th e s t a r t in g R e g is t e r Number” );
S e r i a l . s e tT im e o u t(lO O O O );
m o d b u sS ta rtA d d re ss = S e r i a l . p a r s e ln t ( ) ;
Seri a l . p r in t ln ( “You entered the R egister Number Ox” + String(m odbusStartAddress, HEX));
1f ( a re Y o u S u re ( ))
modbusIndexTX = 7;
m o d b u sA rray[0] = m odbusA ddressC ode;
m o d b u sA rray[1] = 0x03;
m o d b u sA rray[2] = m o d b u sS ta rtA d d re ss >> 8;
m o d b u sA rray[3] = m o d b u sS ta rtA d d re ss & OxFF;
m o d b u sA rray[4] = m o d b u sR e g iste rC o u n t >> 8;
m o d b u sA rray[5] = m o d b u sR e g iste rC o u n t & OxFF;
checkCRC(m odbusIndexTX);
m o d b u sA rray[6] = c a lc u la te d C R C >> 8;
m o d b u sA rray[7] = c a lc u la te d C R C & OxFF;
sendM odbus( ) ;
/ / --------------
/ / end lo o p
/ / --------------
LISTING 1
Once the user enters a menu choice, the switch command uses the integer found to branch to the chosen routine.
circuitcellar.com
Luckily both RS-232 and RS-485 use Internet for less than $20 (and that cost was
the same baud rate, 9600 baud, and use for multiple modules).
the Modbus protocol. Remember, I said the The tiny board in Figure 4 uses a MAX3232
Modbus protocol does not actually call out any to convert the bipolar serial signals (RX and
particular physical interface. We can use the TX) into inverted TTL level (RX and TX). The
RS-232 controller by adding some circuitry larger board in Figure 5 has a microcontroller
to convert RS-232 to TTL and then add an as well as a MAX488 RS-485 driver. The
RS-485 interface. I prototyped this interface microcontroller handles the RS-485's TX and
using two conversion modules found on the RX enables, so you don't have to worry about
them. It will enable TX and disable RX for a
period of time, based on receiving data from
the TX line. I verified that this project works
with a 10A Wanderer controller (Figure 6). This
adds the ability to use this type of controller
with the RS-485 multi-drop system.
LOCAL USE
Since you may be using a similar system on
your property, you may be in range of a Wi-Fi
connection. If so, you are in luck, because the
HUZZAH32 MCU has both Bluetooth and Wi
Fi capability. We've already got a Bluetooth
app, so let's add in some Wi-Fi capabilities to
allow the sniffer to monitor and report some
parameters using MQTT.
MQTT is a standard messaging protocol
for the Internet of Things. It is a lightweight
publish/subscribe messaging transport that
is ideal for connecting remote devices with
FIGURE 5 a small code footprint and minimal network
This PCB is a serial TTL-to-RS-485 converter. In addition, it handles the control of the TX driver and bandwidth. I've used this in many projects in
RX receiver of the RS-485 converter with a microcontroller that monitors the TTL TX line for activity.
the past. My system runs on a Raspberry Pi.
When it senses activity, it enables TX and disables RX. This operation is usually handled by your
The Node-RED application allow you to easily
circuit. (See my September, 2023 column in C irc u it C e lla r [1]).
display the data on a PC (or locally on the Pi)
by pointing to the MQTT port of the Pi's IP in
a browser.
First let's briefly touch on the requirements
for this HUZZAH32 to connect to my LAN, and
connect to the MQTT running on my Pi. The
Wi-Fi uses the W ifi .h library, and MQTT
uses the P u b S u b C lie n t.h library. I have
hard-coded my network name and network
password into the application. This module
will be used in station mode (client), since my
router will assign a local IP to devices that
want to connect. Once it has been assigned an
IP, we can attempt communication with any
other device on this LAN. I have hard coded
my Pi's IP address in the application, so an
attempt is made to connect to the Pi. Once
it connects, we're ready to go. Well, almost.
MQTT requires two additional functions.
The r e c o n n e c t() function is used to
establish a connection with MQTT and, as the
function name suggests, it will also be called
if there should be a loss of connection. Within
this function, you can request a subscription,
FIGURE 6
This month's project is assembled in my office and is used to prove the application written for the
or to be kept up to date on some function
HUZZAH 32 MCU. Beneath the micro is the RS-485 converter. The 3-wire group exiting the PCB is happening elsewhere on the MQTT network.
the RS-485 Modbus connections. For this installment, I am using a Renogy Wanderer. This controller In this case, I subscribe to the DateTime
has an RS-232 output; thus, it uses the circuits shown in Figure 4 and Figure 5 to create a Modbus function. This is an MQTT routine that
connection. publishes the Date and Time every minute.
circuitcellar.com 55
MQTT packets. The PubSubClient.h library The function c lie n t.p u b lis h ( to p ic ,
will handle all the messy stuff. We only need msg) will use the topic and msg arrays to
to supply two arrays, to p ic [ ] and msgEJ. assemble and send an appropriate MQTT
The topic array is the same for all messages, packet to the MQTT application running on my
"ESP32_9592FC". The msg array contains Pi. This is done for each of the solar controller
a JSON-encoded object. JSON (JavaScript registers. Listing 4 shows one of these
Object Notation) is a text format that is registers. You can sample and send data at
completely language independent, but uses a predetermined rate. This is controlled in
conventions that are familiar to programmers. the lo o p O function. For this application, I'm
In its simplest form, a JSON object contains publishing data every minute.
just one member, and the member is in the
form {"string":value}. While this can contain MQTT
multiple members separated by a comma, I'll Assuming MQTT is receiving our published
send just one member in each MQTT packet. data, we can choose to display this from
any browser. If we point our browser to the
MQTT port of the Pi (http://<my Raspberry PI
// batterySOC IP>:1880/), we are brought to the Node-RED
myString=” {\” batterySOC\” :” + String(batterySOC) + application (Figure 7). You can check out a
m yString. toCharArray(msg, msgSize); couple of my past "From the Bench" columns
myString = ID; [3][4] on MQTT and Node-RED, or visit the
myStr1n g.toC h arA rray(topic, m sgSize); websites for MQTT [5] and Node-RED [6] for
c l i e n t . p u b lis h (t o p ic , msg); more information.
Node-RED provides a graphical palette of
nodes that can be used to perform operations
LISTING 4
on your MQTT data. While this might look a bit
After filling in the msg and topic character arrays, the function client.publish(topic, msg) will
intimidating, its pretty easy to understand. In
perform the necessary step to publish the MQTT message.
the upper left of Figure 6 is a pink-colored
■* * r -
r A fr*
FIGURE 7
This column sends JSON elements to my Raspberry Pi running MQTT and Node-RED. MQTT handles all publish/subscribe communications, and routes them as
necessary. Node-RED is a graphical programming language that allows data to be manipulated in many ways. Here the program "flow" gathers MQTT elements and
massages member data so it can be displayed to a user.
circuitcellar.com
ri
•• it f t i r t
•t 1
FIGURE 8
The display page of Node-RED demonstrates the result of my program "flow" in Figure 6. In this case, each chart will display the data received during the last week.
Other data is displayed as text, which is the more appropriate choice.
node that grabs the MQTT data that has is not within reach. My September and
the topic "ESP32_9592FC." This feeds two October columns in Circuit Cellar have been
yellow nodes that separate each JSON object merely a prelude to the last piece of this
member into separate pieces—the topic or puzzle. Although our solar energy system
sensor name, and the payload or sensor value. can communicate using Bluetooth, once we
The switch node then routes each topic to a move off the property, that is no longer
separate output, so each sensor's value can accessible. Although this month's column
be displayed. The blue nodes are two different shows how we might use Wi-Fi, if it were
types of display—a chart or a text box. Most available, we are unfortunately out of range.
of the green nodes are debug nodes that can So what can we do? Next month, I'll use
display raw in the debug panel on the right. something that I've never discussed before.
This group of nodes is known as a "flow." All You might be able to guess what that might
of my present flows can be seen across the be. If not, then you'll just have to wait until
top of the display as tabs. next time, because there is just too much to
Once you have programmed a Node- do and so little time.
RED flow, you can see the results in the
User Interface, a second browser window
at http://<my Raspberry PI IP>:1880/ui/
Additional materials from the author are available at:
(Figure 8). Here the data is displayed in
www.circuitcellar.com/article-materials
real time. You can see the data from the
References [1] and [6] as marked in the article can be found there.
experimental home setup using a small 12V
10W panel. There are five charts and six text
areas. Resources
PRODUCT NEWS
GOWIN Semiconductor & Andes Technology Corp. Announce The First RISC-V CPU and Subsystem Ever
Embedded 22nm SoC FPGA
GOWIN is offering the Andes A25 RISC-V CPU IP and AE350 included a fully controllable high-speed SerDes for communication, P
R
subsystem as instantiated hard cores in its GW5AST-138 FPGA video aggregation, and A l computing acceleration applications O
D
Andes Technology Corporation is thrilled to announce that its that demand very high data rates. Other instantiated functions U
C
AndesCore A25 RISC-V CPU IP and AE350 peripheral subsystem include Block RAM modules supporting ECC error correction, T
N
is hardened and embedded in the GW5AST-138 FPGA chip from high-performance multiple voltage GPIO, and high accuracy clock E
W
GOWIN Semiconductor, the world's fastest growing FPGA company. architecture. These hard functions save the FPGA programmable S
This integration, one of the first complete RISC-V microcontrollers fabric of up 138K LUT's for the designers' unique logic
in an FPGA, provides designers the A25 processor power and implementation."
the peripherals most processors require without consuming any
FPGA resources. This is exciting because the hardware team About the RISC-V Based GW5AST-138 FPGA:
can populate the FPGA with their value-added design while the The AndesCore A25 hard core, running at 400MHz, supports
software team can concurrently create application code based on the RISC-V P-extension DSP/SIMD ISA (draft), single- and double
the rich RISC-V ecosystem. Talk about win-win. precision floating point and bit-manipulation instructions, and
"In the Arora V family, we incorporate the peripherals that MMU for Linux based applications. The AE350 AXI/AHB-based
a RISC-V CPU typically requires in hard instantiations," says platform comes with level-one memories, interrupt controller,
GOWIN's Sr. Director of Solution Development, Jim Gao. "We debug module, AXI and AHB Bus Matrix Controller, AXI-to-AHB
Bridge and a collection of fundamental AHB/APB bus IP components
pre-integrated together as a system design. DDR3 controller and
SPI-Flash controller in the FPGA fabric back up the A25's 32KByte
I-Cache and D-Cache after cache misses. Off chip DDR3 provides
data memory, SPI-Flash contains the A25's instruction memory
(codes copied from SPI-Flash into DDR3 and Cache upon boot
up). Besides hard instantiated functions, the GOWIN GW5AST-138
FPGA fabric affords 138K LUTs for custom design implementation.
GOWIN EDA provides an easy-to-use FPGA hardware development
environment for the Arora V. The environment supports multiple
RTL-based programming languages, synthesis, placement and
routing, bitstream generation and download, power analysis and
in-device logic analyzer.
Answer 1—The term "virtual" is confusingly overloaded Answer 2—The PDP-11 family of minicomputers from
in these discussions. You need to have virtual addressing Digital Equipment Corporation (the first machines on
in order to have virtual memory, but you don't necessarily which Unix was run outside of Bell Labs) had 16-bit virtual
need to use virtual memory if you have virtual addressing. addresses, providing up to 64kB of memory per process
A memory management unit (MMU) creates virtual, or (128kB on some models that had separate I and D spaces).
"logical," address spaces, and maps them, page by page The physical address was either 18 or 22 bits, allowing up
(or segment by segment), into the physical memory that is to 4MB of physical memory.
present on the machine. Usually, each process running on Similarly, the HD64180, Hitachi's contribution to the Z80
the machine gets one of these logical address spaces to run family of 8-bit processors, also had 16-bit virtual addresses,
in, and it basically starts at address zero and goes as high but either 19- or 20-bit physical addresses, allowing up to
as needed. 1MB of physical memory.
This has several advantages. The first is protection: if no
mapping to a particular physical page exists in the current
process's logical address space, then that process cannot
affect that page in any way. Answer 3— Virtual memory means that any memory
The second is the ease of dynamically allocating physical access made by the CPU might not succeed immediately,
memory to processes: pages that are contiguous in the resulting in what is generally called a "page fault," sometimes
logical address space do not need to be contiguous in signaled by a "bus error." The key feature required of the
physical memory. One example of this is managing stack CPU is that it must be able to suspend the execution of the
space. Suppose you allocate 16 4KB pages (64KB) initially instruction that caused the page fault in order to service the
for a process's stack, but it turns out to be a deeply bus error, and then resume that instruction and complete it
recursive process that needs more. As soon as it touches correctly when the page has been loaded.
the first location outside the allocated area, an exception For example, this is the key difference between the
will occur and the underlying handler will have the option of Motorola 68000 and the 68010 that followed it. The very
assigning additional physical memory to that process for its first engineering workstations were based on the 68000,
stack. When the handler returns, the process will continue and they had to resort to some bizarre tricks to be able
as though it had had that memory all along. "Heap" space to handle bus errors for virtual memory. Some went so
can be grown as needed in the same way. far as to include a second 68000 chip whose only purpose
Memory can be shared by having two or more logical was to handle the page faults while the primary CPU was
address spaces map some of their pages to the same set suspended, waiting for its memory access to complete. The
of physical pages. You can even set this up so that only one 68010 has the ability to save enough of its internal state on
process at a time has "write" permission for the pages. the stack so that it can resume an instruction in the middle
Finally, you can do virtual memory if you want. Virtual of execution, allowing it to handle its own page faults.
Q
memory simply means that not all of the memory pages are
E actually in physical memory at all times—some of them are
R
U swapped out to disk storage. This allows the total number
O
Y of pages to be larger than the amount of physical memory Answer 4— Virtual addressing can help with running
S
T that is actually present on the machine. All this means is large applications. Instead of using "overlays" to handle
S
E that there's an entry in the logical address map for a page, large amounts of program code, the application can be
but there's a "not present" flag set and a disk address is divided into multiple tasks, each of which runs in its own
stored in the map instead of a physical memory address. virtual memory space. The tasks can communicate and
When the process touches the page, it gets suspended until synchronize with each other using facilities provided by the
such time as the I/O can be done to bring the page into operating system. For example, this is a key feature of Unix
memory. Then the mapping is updated to "present" and the running on a PDP-11.
new physical address of the page, and then the process can
be resumed.
cuitcellar.com/subscription
circuitcellar.com 61
The Directory of
Advertisers must furnish digital files that meet our specifications (www.circuitcellar.com/mediakit).
All text and other elements MUST fit within a 2" x 3" format.
E-mail adcopy@circuitcellar.com with your file.
www.embeddedARIVI.com
TS-7100
NXP i.MX 6UL 696 MHz ARM CPU w ith FPU
Our smallest single board com puter
*jjembeddedTS
62 CIRCUIT CELLAR • OCTOBER 2023 #399
ith the electrification of light vehicles and trucks replacing fossil fuels
as an energy source, the traction inverter is the most important power
conversion and delivery subsystem of the electric vehicle (EV) powertrain.
A traction inverter's role is to convert the EV battery's high-voltage DC
to the AC that the electric motor needs. The traction inverter controls the speed and
torque of the motor, and the efficiency of the traction inverter has a direct impact on
the power and thermal dissipation of the system, as well the EV's driving range over
a single battery charge. "Traction" indicates the act of pulling the EV over a surface in
coordination with the motor. As traction inverter power levels approach 300kW, reducing
energy losses throughout the drive cycle is the number one design consideration for car
original equipment manufacturers worldwide.
To improve efficiency, the industry has widely adopted silicon carbide (SiC) field
effect transistors (FETs); the isolated gate drivers that power these switches, as shown
in Figure 1, have become more sophisticated, and now include isolated analog-to-digital
George Lakkas converter sensing, multiple modes of overcurrent protection, bias supply monitoring,
Product Marketing Engineer, gate monitoring, programmable safe states, built-in self-test and a new feature called
real-time variable gate-drive strength.
High Power Drivers Additionally, depending on the Automotive Safety Integrity Level (ASIL) functional
safety requirements, the gate-driver integrated circuit (IC) may have to be International
Organization for Standardization 26262-compliant, ensuring fault detection of >99%
and >90% for single and latent faults, respectively.
In this article, I will focus on the benefit of real-time variable gate-drive strength on
improving SiC FET switching losses and efficiency, and therefore extending EV operating
ranges.
t2 t4
P sw_T = j u(t)i(t) dt+ j u(t) i(t) dt ^sw
*3
traction inverters in automotive applications [1]. Its gate SiC slew-rate control by varying gate-driver IC drive strength
temperature is cold, then it's best to use a driving profiles), the battery is <80% full,
weak gate-drive strength. If the load current and the temperature is room or warm, then
is low (which is true for the majority of EV employ a strong gate-drive strength. The
control logic should include parameters such
FIGURE 6
as phase current, current threshold, and
800V, 300kW SiC-based traction external gate resistor values.
inverter reference design data Figure 5 summarizes the criteria, while
the results in Figure 6 illustrate how the
combined drive with variable strength in the
High-Power, High-Performance Automotive
SiC Traction Inverter Reference Design enables
lower power losses in the power module,
maintaining stable thermal performance [2].
So, what does this mean for the ultimate
goal—longer range? Consumers choose EVs
today for their reliability, performance, and
looks, but range is an important decision
Output Current [A]
factor.
CONCLUSION
With EV traction inverters approaching
300kW power levels, the need for higher
reliability and higher efficiency is imperative.
SiC-isolated gate drivers with real-time
variable gate-drive strength are useful in
achieving these goals. The UCC5880-Q1
comes with design support tools including
evaluation boards, user's guides, and a
functional safety manual to assist you with
your designs up to ASIL D.
Additional materials from the author are available at: ABOUT THE AUTHOR
www.circuitcellar.com/article-materials
George Lakkas George Lakkas has been in the power supply
References [1] to [2] as marked in the article can be found there.
and power management IC industry for 33 years, having held
positions as a power supply test engineer, assistant design
RESOURCES
engineer, applications engineer, product marketing engineer,
Texas Instrum ents | www.ti.com
product marketing manager, and product line manager for power
management ICs. Since joining TI in 2006 George has worked in
various product marketing roles for non-isolated DC-DC conversion
solutions, and currently is a product marketing engineer for
automotive traction inverter isolated gate drivers. George lives in
Raleigh, NC.
©TDK
pPOL™ Chip-Embedded
Power Modules
A Simple Solution for High Power Density Applications
Current Output: 3 A, 4 A, 6 A, 12 A
REGISTER FOR
Wide Input Voltage (up to 16 V) A FREE pPOL
EVALUATION
Adjustable Vout ±5m V
BOARD
Output Voltage, ±0.5% Initial accuracy (Up to 5 winners)
Powered by the NXP i.MX6 SOC w ith the Arm® Cortex®-A9
core, theTS-7970 industrial Single Board C om puter (SBC)
stands o u t from the crowd w ith its high perform ance
com ponents, connectivity options, and m ultim edia
capabilities. It's a general purpose, low -pow er SBC ready
to tackle dem anding applications including digital signage,
HMIs, data acquisition, Edge loT, industrial autom ation,
and anything in between.
to 2 GB DDR3 RAM
3 4 G B M L C e M M C Flash
* ^ M a d e in USA
h ^ ^ V w ith Global Parts ^embedded Io