Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

DRONE DEVELOPMENT

AUGUST 2023
c irc u itc e lla r.c o m ISSUE 397

circuit cellar Inspiring the Evolution of Embedded Design

I Application-Specific MCUs

I Debugger on Arduino IDE | Watchdogs in Embedded Linux |

Al Apps with SenseCAP K1100 I Thermal Basics |

Finding Bugs in Real-Time Systems | PC User Interface

The Future of Embedded Code Development


circuit cellar Q™ 1 circuit cellar ■ » circuit cellar circuit cellar
EMBEDDED PCs SUIT UP FOR EMBEDDED SOLUTIONS L TFT UP EMBEDDED SYSTEMS ENABLE DRONE DEVELOPMENT KITS
SMART TRANSPORTATION S M A R T C IT IE S CONDITION MONITORING EMPOWER HANDS ON DESIGNS
Get the complete Circuit Cellar issue archive and article code stored on a
stylish, durable and portable USB flash drive. You can easily keep your CC
Vault archive up to date by purchasing subsequent issues from our webshop
or by downloading issues with a Circuit Cellar Digital Subscription. Issues
appear in searchable PDF format.
cc-webshop.com
circuit cellar >circuit cellar i circuit cellar circuit cellar
ADVANCES IN THE
MODERN RAILWAY SYSTEM
G
HYBRID AND ELECTRIC
VEHICLE SOLUTIONS
e PCB INNOVATIONS
in
WEARABLE DEVICES

nun linn ■m
2 CIRCUIT CELLAR • AUGUST 2023 #397

Issue 397 August 2023 | ISSN 1528-0608

CIRCUIT CELLAR® (ISSN 1528-0608) is published monthly by:

J N ^ lt a g e KCK Media Corp.


PO Box 417, Chase City, VA 23924

Periodical rates paid at Chase City, VA, and additional offices.


One-year (12 issues) subscription rate US and possessions
$50, Canada $65, Foreign/ ROW $75. All subscription orders

On The Frequency Illusion payable in US funds only via Visa, MasterCard, international

w
postal money order, or check drawn on US bank.

hen I was a kid, my mom bought a white Chrysler LeBaron. Soon SUBSCRIPTION MANAGEMENT
after, I noticed that a disproportionate number of cars on the road
Online Account Management: circuitcellar.com/account
were also white Chrysler LeBarons, and I wondered how I had never Renew | Change Address/E-mail | Check Status
noticed this trend. My mom explained to me that when you notice
CUSTOMER SERVICE
something for the first time, you tend to see it more often in other places too.
It turns out, of course, that she was right. Recently, I learned that this E-mail: customerservice@circuitcellar.com
phenomenon is known as the "frequency illusion." The current consensus is that it's Phone: 434.533.0246
the result of a combination of selective attention and confirmation bias. And one of Mail: Circuit Cellar, PO Box 417, Chase City, VA 23924
the most commonly given examples of the frequency illusion is an observer noticing
similar cars on the road—red cars, for instance. Postmaster: Send address changes to
Circuit Cellar, PO Box 417, Chase City, VA 23924
This tidbit of information doesn't make the actual experience of the frequency
illusion any less eerie when it happens. Certain themes—phrases, behaviors,
NEW SUBSCRIPTIONS
concepts, objects—will suddenly seem to be everywhere in my life, sometimes to
the point where it's hard not to succumb to the idea that I'm experiencing a glitch circuitcellar.com/subscription

in the matrix.
For that matter, maybe I am! Or, to ground my tech anxieties a little bit more in ADVERTISING
the here and now: how often is this frequency illusion not an illusion at all, but the
Contact: Hugh Heinsohn
real experience of my various smart devices sending me hyper-targeted marketing
Phone: 757-525-3677
that reinforces what I'm thinking about and engaging in, which in turn reinforces
Fax: 888-980-1303
the targeted marketing I'm (constantly) receiving?
E-mail: hheinsohn@circuitcellar.com
These days, I'm noticing embedded systems absolutely everywhere. As the Advertising rates and terms available on request.
editor of this magazine, thinking often, when I'm not working, about articles I'm
currently editing, or mulling over ideas for the next editor's letter, I feel like I've NEW PRODUCTS
been dropped in a world where everything around me has a little semiconductor
E-mail: product-editor@circuitcellar.com
heart beating somewhere inside it.
I notice it most when electrical devices have quirks. Our house's thermostat has
HEAD OFFICE
this maddening behavior in which, when we lower or raise the temperature by just
one degree Fahrenheit, it will change the allegedly measured ambient temperature KCK Media Corp.

of the room to that set temperature without actually kicking on the air conditioning PO Box 417
Chase City, VA 23924
or heat. I found this baffling and, if I was in the right mood, infuriating. Is my Phone: 434-533-0246
thermostat trying to gaslight me? Is it merely lazy and prefers not to turn on, right
now? Then I read Joseph Corleto's piece in this month's issue introducing control
COPYRIGHT NOTICE
systems. Now, although I don't have access to the programming logic used for my
thermostat, I suspect it's a bit of "hysteresis," most likely used to prevent excessive Entire contents copyright © 2023 by KCK Media Corp.

wear and tear of our heating/cooling system's components. Knowing this makes that All rights reserved. Circuit Cellar is a registered tradem ark
of KCK Media Corp. Reproduction of this publication in
quirk a little less aggravating when it pops up. whole or in part without written consent from
So, if knowledge is not quite power, it can at least be somewhat calming. With KCK Media Corp, is prohibited.

the rapid "embeddification" of everything, it's hard to say if my experience with


embedded systems is reducible to the frequency illusion, or if it's a concrete, real- DISCLAIMER
world phenomenon. But as everything becomes more and more connected, and
"smart," and quasi-"sentient," it would be very difficult indeed not to succumb to KCK Media Corp, makes no warranties and assumes no
responsibility or liability of any kind for errors in these
some magical thinking were it not for the fact that I get to read so many exceptional programs or schematics or for the consequences of any such
articles on embedded design, each month. So, here's to our writers, for keeping me errors printed in Circuit Cellar®. Furthermore, because of
possible variation in the quality and condition of materials and
(somewhat) grounded. And thank you for reading.
workmanship of reader-assembled projects, KCK Media Corp,
disclaims any responsibility for the safe and proper function
of reader-assembled projects based upon or from plans,
Editor's note: In Brian Beard's "Arbitrary descriptions, or information published in Circuit Cellar®.

Function Generator" article in Circuit


The information provided in Circuit Cellar® by KCK Media
Cellar's July #396 issue, we included an Corp, is for educational purposes. KCK Media Corp, makes
incorrect URL for the Lucid Technologies no claims or warrants that readers have a right to build
things based upon these ideas under patent or other
website. The correct address is relevant intellectual property law in their jurisdiction, or
www. lucidtechnologies. info. that readers have a right to construct or operate any of
the devices described herein under the relevant patent or
other intellectual property law of the reader's jurisdiction.
The reader assumes any risk of infringement liability for
constructing or operating such devices.

© KCK Media Corp. 2023 Printed in the United States


swallace@circuitcellar.com
circuitcellar.com 3

OUR NETWORK

circuit cellar

P Evaluation of Debugger on Arduino IDE V2.0.4

(press By Aubrey Kagan


VOICE 1COIL
I f h LOUDSPEAKER
N^SOURCEBOOK
12 Watchdogs in Embedded Linux
For More Robust Solutions
By Pedro Bertoleti

SUPPORTING COMPANIES
CCS, Inc. 61
16 Prototype A l Apps with SenseCAP K1100
Part 2: Dog Detection and Deterrence
By Raul Alvarez-Torrico
Digi ConnectCore 62
TECHNOLOGY FEATURE
EmbeddedTS 61, C4
Drone Development and Usage By Michael Lynes
Renesas 31
DATASHEET
Siborg 11 Application-Specific MCUs
For Niche Embedded System Solutions
TDK C3 By Sam Wallace

NOT A SUPPORTING The Magic Smoke Factory


COMPANY YET?
Intro to Control System s COLUMNS
Contact Hugh Heinsohn
hugh@circuitcellar.com, Part 1: Meet Our Plant
Phone: 757-525-3677, By Joseph Corleto
Fax: 888-980-1303
Start to Finish
to reserve space in the
next issue of Circuit Cellar. 41 Why's It So Hot in here?
Therm al Basics
THE TEAM
By Stuart Ball
FOUNDER Steve Ciarcia
PUBLISHER KC P rescott
Embedded in Thin Slices
CONTROLLER Chuck Fellows Debugging Embedded Real-Time System s
EDITOR-IN-CHIEF Sam W allace
SENIOR ASSOCIATE EDITOR S trategies fo r Finding Bugs
Shannon Becker By Bob Japenga
TECHNICAL COPY EDITOR
From the Bench
CONTRIBUTING EDITOR
Carol Bower

Brian M illie r
50 I2 C User Interface (I/O)
PROJECT EDITORS Ken Davidson Button I t Up
David Tweed
GRAPHICS Grace Chen
By Jeff Bachiochi
MARKETING MANAGER Tori Zienka
TECH THE FUTURE
ADVERTISING SALES REP.
Hugh Heinsohn
The Future of Embedded Code Development
ADVERTISING COORDINATOR
Tools Best Suited For Its Unique Requirem ents
H eather C hildrey
By Rafael Taubinger
COLUMNISTS
Jeff Bachiochi (From the Bench)
59 : Product News
Stuart Ball (Start to Finish)
Joseph Corleto (The Magic Smoke Factory)
Bob Japenga (Embedded in Thin Slices)
62 : TEST YOUR EQ
Brian Millier (Picking Up Mixed Signals) @editor_cc
Colin O'Flynn (Embedded Systems Essentials) ©•circuitcellar circuitcellar circuit_cellar
4 CIRCUIT CELLAR • AUGUST 2023 #397

Evaluation of Debugger on
Arduino IDE V2.0.4
S
E By
R
U Aubrey Kagan
T
A
E
F

Noticing a lack of available—materials


on the Arduino Debugger, I took it upon
myself recently to draft something of
an introductory "user manual" for this
software. Hence, this article!

recently joined a maker space in order


I discovered that there was a recent

1 to have access to their equipment for


a hobby project I'm working on. The
project has taken a turn and it looks
upgrade to Arduino IDE v2, which included
a debugger that worked with a different
microcontroller (MCU) within the Arduino
like I'm going to need either a servo motor family, including the Arduino Zero board. The
or some robotics, so it was opportune when
one of the maker organizers put on a series of
debugger required some additional hardware
for interfacing, but one option, the Atmel
three presentations on the Arduino Integrated Embedded Debugger (EDBG), is included on
Development Environment (IDE) v l and the the Arduino Zero board. It adds to the cost
Arduino UNO. As part of the discussions, of the board, but there are knockoffs without
the presenter showed two or three YouTube the EDBG, so that you can develop on the Zero
videos that demonstrated simple aspects and then download to the cheaper board when
of interfacing the Uno board with external development is over. I decided that debugging
devices, like a pushbutton switch. There were in the newer environment would be the topic
so many blatant errors that I was forced to of my first presentation.
put my hand up and correct them. I started research on the Arduino Debugger
Me and my big mouth! I won't say that but could only find the basic description of its
I was volunteered to run an Arduino group, operation [1] and one forum thread about a
but it wouldn't be far from the truth. The idea breakpoint problem. I experimented with
was that there would be a presentation every this debugger, and it has an impressive array
month, followed by a discussion, workshop, of features that resemble those in other
and anything else that might arise. debuggers. Unfortunately, some of those
I've been in the electronics business since features were problematic, either because
1976, before there were even assemblers, the programming is incomplete, or there is
to say nothing of compilers or any form a flaw in the programming. I thought I would
of debugging. I clearly remember the old write a "user manual" for the attendees of
times, and believe me, when it comes to my presentation. While I was preparing it, it
microcomputer programming and testing, occurred to me that there might be a wider
those were not the "good ol' days." It struck audience, and perhaps my criticism might
me that the Arduino Uno/IDE v l was not lead to improvements, hence this article.
that far removed from those times, compiler The words "debugger," "debug," and "bug"
notwithstanding. Any debugging was based have contextual meanings and are used with
on implied observations. You can only activate such gay abandon that I thought I ought to
I/O pins to indicate execution of portions of define their usage in this article. A "debugger"
code or log some text to the internal IDE is a combination of hardware and software
monitor. I had no intention of reliving my that allows the user to stop and start the
initiation into electronics. operation of the target MCU both at random
circuitcellar.com

and specific points during the execution of


the software. The debugger also enables
the inspection and modification of variables.
This combination allows the user to analyze
the program flow and correct errors that
are embedded in the software. "Debugging"
is the process of using the debugger, and a
"bug" is an error in the user code.

SETUP
To start, install the SAMD21 Core for
MKR boards. You can find a link to Arduino's
instructions for this task on C irc u it C ellar's
Article Materials and Resources web page
[2]. Next, connect the Arduino Zero to
a USB port and listen for the audio tone
indicating recognition. Again, head to the
Article Materials page for an Arduino link that
identifies the location of the programming
USB port [3].
Start the Arduino IDE with an existing
program or a blank sketch that resembles
Figure 1. Each time you start the debugger,
verify by checking under the Tools menu
that the board selected is the "Arduino Zero
(Programming Port)." If not, drill down to
select that board. The selection is confirmed
in the box identified as "D" in Figure 1. FIGURE 1

Ensure that the correct COM port is selected Arduino IDE with a sketch uploaded and relevant controls highlighted
by clicking on the Tools menu and looking at
the Port line. Under the Sketch menu, ensure
that "Optimize for Debugging" is checked.
2

CODE j
4
The program I have written is a trivial ■3 /O ld s**r u p ( ) (
sketch to try and help understand the A
? p in r tx M L E D BU1LT1H, OUTPUT);
features of the debugger. It simply increases *

a global variable i U t i l i t y from the value of


10 jr s ig n e d s h o r t 1U t i l i t y - 0;
0 to 65,535 (16-bit unsigned integer), after 11
which it rolls over to 0. This carries on ad 12
13 1 I t LAddOno( ^ s ig n e d Irt W lU tb o r)
infinitum. The program will flash the onboard U
LED once every second, but the LED is only off 15 v o id lo o p ( ) f
16
for 125ms while it is on for 875ms. The three 17
least significant bits of i U t i l i t y increment 15
Ifl
from 0 to 7 continuously, and the program 20

looks for when all three bits are 0, which 21


22 If ( ( iU tlllty i > 0) {
happens for 125ms during the 1-second cycle. 23 d i g i t a l l y ite ( L E D B U IL T IH , H IG H );

If the three bits are 0, the LED is turned off. 24


25 ; C-SC [
In any other case, the LED is turned on. For 26 d !fflta W rlte (L E D _ B IJ T L T T N ( LCW>;
77
every path through the loop, the process J 1
l

28
waits 125ms, which admittedly is rather poor 2?
30 W ttllty - 1A d lO r* ( W t 11 i t y )
programming practice since the program 31
could be doing something else instead of just 32
33
hanging around waiting for time to pass. This 34 1-iy ( i 2 > );
is just for a simple program. JJ
36
Ratherthansimplyincrementing i U t i 1i ty , 3? jH iig n a d Lnt lA d d O r ^ (ijn s ig n M l I n t iN tm b r r )
I chose to create a function (iAddOne) that id H i s . i n t ji;
30 iJ • iN H a h o r;
increases the value of the parameter passed 40 1 1 **;
to it and returns the increased value. Again, 41 11;

this is to help understand the features of the


debugger. The code from Figure 1 is shown FIGURE 2
magnified in Figure 2. The code is included The code for the simple program used to showcase the Arduino Debugger
CIRCUIT CELLAR • AUGUST 2023 #397

in the ShowDebug.ino Arduino sketch on time the user program has been run. Once
Circuit Cellar's Article Materials and Resources open, that tab must be manually closed or will
web page. always appear every time Arduino is invoked
for a given sketch. It's easy to close by clicking
START DEBUGGING on the "x" on the right side of the tab.
One of the issues I have with the Arduino A consequence of inadvertently invoking
IDE v2 Debugger is that it allows you to the lower "Start Debugging" (item E in Figure
m odify the code even when the debugger is 1) is that you may end up with a duplicate
running, so there can be a m ism atch between source file, an artifact that is impossible to
the code on the screen and the code that is get rid of as shown in Figure 3. There is a
being executed, as well as some weird issues further disadvantage in that the lower "Start
like breakpoints in locations different from Debugging" (item E in Figure 1), is near the
where they were set. All this is to say that it's run/stop icon (item K in Figure 1) and is easily
good practice to com pile the program before confused with the continue icon, with irritating
starting a debug session. Com pilation is consequences like the artifact just mentioned.
invoked by clicking on the check m ark on the Unlike all the other debuggers that I have
top left of the screen (button A in Figure 1). ever used, the Arduino Debugger begins
You can start debugging by clicking on the execution of the user program immediately.
Start Debugging icon (button C in Figure 1), I could think of some reasons why I think this
to the right of the com pile icon. Although the should not be, but in truth, it's probably that
lower icon (E in Figure 1) also claim s to start old habits die hard.
the debugging, it has a different function
and, pending furth er investigation, should be BREAKPOINTS
avoided. Buttons E, F, and G in the bounded A breakpoint stops the execution of the
section of Figure 1 are all puzzling and will user program before the line chosen as the
be discussed later in the "Th read s" section of breakpoint. A breakpoint is set by clicking
this article. to the left of the line number; a brown dot
Button H in Figure 1 turns on the Debug indicates its establishm ent. You can see one
Console beneath the program if it has not such breakpoint on line 7 of Figure 2. One of
already been opened. Closing the debug window the m ethods to clear a particular breakpoint
is a function on the Debug Console itself. is to click over the existing breakpoint dot. We
Running ahead a little, if the program is will get to other methods shortly.
stopped during execution of the code included There is a flaw in this version of the
in a library, the associated code will appear in debugger. It must be paused before placing
a tab, like the "delay.c" and "m ain.cpp" tabs the first breakpoint. If not, the visibility
in Figure 1 (labeled S and T in the figure). The of the breakpoint dot is irrelevant, and
tabs normally become noticeable after the first the breakpoint will stop the code at the
breakpoint's original placem ent until the IDE
is exited and restarted. Since the code starts
A rd u in o
immediately, you need to establish a habit
whereby you clear all the breakpoints before
DEBUG S liuv-D ubkig ino t-butl tip
invoking the debugger, and then the first
thing you do on starting to debug is to pause
the code by clicking on button K in Figure
. THREADS 1. Thereafter you can place breakpoints
inr ( L L D _ B U IL 1IN , OUTPUT); w ithout concern as to w hether the processor
ti is running or not. Note that any breakpoints
that exist at startup, irrespective of if it was
R
C A LL STACK
the reason for the debugger break, will cause
VARIABLES 9 in t lAddOne(unsigned in t iHumber)
the same problem.
An alternative approach is to set and leave
a breakpoint in the setup code as in line 7 of
i l i t y A 0x7) > 0) { Figure 2. All other breakpoints must be cleared
14 LWrite(LED_BUILTIN, HIGH); before invoking the Arduino Debugger. In this
way, every time the processor is reset, execution
MUCH
J
will stop at line 7, allowing you to prepare for
the running of the program and thereby solving
Outnui Dsibutj Cwsote x
BRtAKPUlhir 5
two of my concerns in one shot. That breakpoint
can even be set before the debugger is invoked.
Unfortunately, this approach does sacrifice one
FIGURE 3 of the four allowable breakpoints, which we will
Duplicate source file, and impossible to get rid of discuss shortly.
circuitcellar.com

Since this is important, I will repeat it. Any Hover the mouse over any occurrence of
breakpoint that exists at startup (even multiple the 1U t i l i t y variable (E in Figure 4) when
breakpoints) will cause the same problem. the user program execution is paused. The
Make it a practice to clear all breakpoints value that pops up is that variable's current
before closing or starting the Arduino value. It can be shown in decimal or hex
Debugger, apart from my suggestion of the notation, and it can be toggled by right­
breakpoint in the setup code. Breakpoints are clicking on the Global entry of the VARIABLES
preserved on exiting the IDE and restored on section (actually any of the sections) on the
restarting the sketch. left of the screen (C of Figure 4) and selecting
Start the execution of the user program, either "Enable Hex Mode" or "Disable Hex
if it's not already running, by clicking on the Mode." Unfortunately, this is a global setting,
continue/pause button—button K in Figure 1. so you cannot have some variables in decimal
If the program is already executing, button K and others in hex at the same time. I will
is a pause symbol (two vertical parallel lines), further discuss variable values later in this
as pictured in Figure 1. If the user program is piece.
paused, the icon on the continue/pause button Clear the breakpoint by clicking the brown
changes to the one seen as button B in Figure 4. dot to the left of line 22, and continue execution
Clicking on the continue/pause button will start of the code. Notice that the processor now
execution from the place where it was paused. continues without breaking.
Verify that the onboard LED flashes. Pausing execution by clicking on the Run/
Staying with Figure 4, if the ShowDebug. Pause button will stop execution at some
ino tab is not selected, click on it now. Let's random spot. If the program is not performing
establish a breakpoint by clicking in the as expected, you can examine the location of
breakpoint column to the left of line 22. The the code to see if the program has "locked
program screeches to a halt, indicated by the up." You can set a breakpoint and continue, or
five-sided figure surrounding the breakpoint simply continue with the execution.
dot symbol shown at line 22 indicated as A in Now, set a breakpoint at line 26 and start
Figure 4. The five-sided figure represents a execution. The program only executes this line
pointer to the next line that will be executed. every eighth time through the program loop.
Click the Run/Pause button (B in Figure The program should halt at the breakpoint.
4) to continue operation. Note that execution Next, set a breakpoint at line 23, leaving the
stops at the breakpoint again. Because it's a breakpoint at line 26 untouched. Resume
loop, this will go on and on. running the program every time the program

StnwCtatajg ino d&id'f £ nid.h cpp

4
rtd « t u p ( ) {
PAUSED ON fjRE AKPOIN1
pinHodef LEDBUILFIMf CUTPUT),
a

10 e;

CALL S tA C H in t r

Or ShowD#bug ms P T )
main cpp

1*

VARABLL5

> lo ca l
f
23 d R1 t f { . F D R U L T tN , HIGH);
24
UAokt&nfi □ ) * !* • {
C l g i ‘ d ? .-L te (L £ D B U IL T lH r LOW);

WAT CM

10 1U t i l i t y
D

d e la y (12 ;
Q StwwDebug ino i । .■>«. i
36
n s lg n e d lo t . i’ lo t <'
JB u n s ijn e d j

40 FIGURE 4
11; Setting a breakpoint and halting
2
operation
CIRCUIT CELLAR • AUGUST 2023 #397

and can be re-enabled by clicking on the


WATCH
blue box again. The color of the breakpoint
dot changes from brown to gray to indicate
a disabled breakpoint (this may depend on
the IDE theme). This feature can be useful
in enabling and disabling a breakpoint in a
"distant" part of the code, without searching
the code and finding it again. It appears
that as long as there are only four enabled
breakpoints when the user program resumes
you can have more breakpoints listed, but I
have no idea of the maximum number.
When the mouse hovers over the top
righthand corner of the BREAKPOINTS window,
three icons appear, marked B, C, and D in Figure
5. B allows you to add a "Function Breakpoint,"
although I am not sure how a Function
Breakpoint differs from a regular breakpoint,
FIGURE 5 nor how you go about adding a breakpoint
Breakpoints listing encounters a breakpoint. Start counting the using this method. Item C will enable/disable all
number of times it hits the breakpoint at line breakpoints simultaneously. You should remain
23 before it hits the breakpoint at line 26. It aware if it has been activated (all breakpoints
should break seven tim es at line 23 before disabled) because it is an overriding and
it executes line 26 on the eighth time. This latched function. Setting a new breakpoint with
indicates that your program is executing this option enabled will establish a disabled
correctly. breakpoint. The setting is preserved through
I'm not sure how many breakpoints can IDE shutdown. D will clear all breakpoints.
be set, but it appears to be at least four. Right-clicking on any breakpoint entry
Although the IDE appears to allow more than either in the breakpoint window or on the dot
four, exceeding four generates an "Exception in the breakpoint column provides the ability
has occurred" message when the program to clear/disable the individual breakpoint.
resumes execution, and the phantom It's also possible to edit the breakpoint by
breakpoint problem reappears. You must right-clicking on any breakpoint entry either
close the IDE and start again to get back to in the breakpoint window or on the dot in
normal operation. the breakpoint column. On selecting Edit, a
I've noticed that sometimes the program line pops up over the code with a dropdown
seems to break one instruction past the menu as seen in Figure 6. Clicking on one of
breakpoint. At this point, I have no idea if this the three options will generate a description
is a finger problem of my own making (like of the selection in the line to the right of the
inadvertently touching the return button and drop-down box. Note that the <Esc> key will
modifying the source code) or a flaw in the allow you to exit w ithout changing anything.
software, and I cannot duplicate the problem Expression option: The Expression setting
consistently. My only solution is to exit the IDE enables the breakpoint every time the entered
and start from scratch. expression is true. Let's say we want the
Notice on the lower left-hand side of the IDE program to pause every time the variable
is a "BREAKPOINTS" window (D in Figure 4), i U t i l i t y is 0. Delete all breakpoints. Set
and that each breakpoint appears in this a breakpoint at line 22. Right-click on the
window. On the left side of each entry is a breakpoint dot and select Edit Breakpoint.
checkm ark in a blue square (A in Figure 5). Select the Expression option from the drop­
Notice the line number on the right-hand side down menu and in the line to the right,
of each entry indicating which breakpoint it is enter ( i U t i l i t y & 0 x 0 f)= = 0 followed by
identified with. <Enter>. Notice the use of C notation. The
Clicking on the checkm ark disables the IDE is not sm art enough to autocomplete the
breakpoint. The breakpoint is left in location variable and cannot detect an error in the

FIGURE 6
Editing breakpoints options
circuitcellar.com

expression. The solid breakpoint dot changes the same way as before, and see that it has
to a circle with a small line in the middle. increased by one.
Allow execution of the user program to Click the Step-Over button again and
continue until the breakpoint is activated. Note note that the 5-sided pointer is now at line
that at each pause, the four least significant 35, which is the end of the loop. Resume the
bits of the variable value are 0. execution by clicking the Run/Pause button.
Hit Count option: The Hit Count setting The program should halt once again at line
allows a breakpoint when the line has been 30. This time, click on the Step-Into button
executed N times. Delete all breakpoints. Set a (button M in Figure 1). Note that this takes
breakpoint at line 30 and one at line 34. Right­ you into the iA d d O n e function. If you hover
click on the breakpoint dot of line 34 and select over the local variables ( i l and i Number)
Edit Breakpoint. Select the Hit Count option you can see their values.
from the drop-down menu and in the line You could step over the next instructions
to the right, enter the number 3 followed by using either Step-Over or Step-Into, but if
<Enter>. The solid breakpoint dot changes to a you are satisfied with the operation of the
circle with a small line in the middle. function, you could click on the Step-Out
Allow execution of the user program to button (N in Figure 1), which will return you
continue. Count the number of times the to the calling step of the program.
breakpoint at line 30 is encountered before If you chose to step through the end of the
the breakpoint at line 34 is encountered. It main program loop, the debugger seems to
should be three times. There appears to be get lost. But this is nothing too problematic,
a persistence and/or value problem with this and can be cured by sim ply clicking on the
breakpoint setting after the first time it is Run button.
encountered, and I cannot find any consistency,
but it does work for the first time. THREADS
Log Message option: The description that The Arduino debugger appears to offer
appears on the right of this option is "Message support for "threads," although there is no
to log when breakpoint is hit. Expressions explanation as to what these threads are or
within {} are interpolated. 'Enter' to accept, how to define them. As far as I've been able
'esc' to cancel." If you enter a message within to establish, to date the Arduino IDE does not
quotes—for instance, "breakpoint reached"— support a thread structure, but there are some
this message will appear on the Debug user-provided libraries that will approximate
Console if it is visible (button H in Figure 1) the approach. There are also some modern
every time the breakpoint is encountered, but processors that have multiple cores. Perhaps
the micro will not stop. that is what is meant. In either event, until
I am unsure what "expressions within {} we can figure out precisely what is going on,
are interpolated" means. When I tried to enter I would recommend avoiding these options
some test expressions to see the effect, it entirely.
produced a diamond shape in the breakpoint The drop-down menu (F in Figure 1) to
margin and the whole system froze, requiring the right of the Start Debugging button (E in
exit of the debugger state. Given all the other Figure 1) allows you to add a configuration, but
debugging capabilities, I am not sure what selecting it introduces a new boilerplate source
benefit this feature offers and I would love to file and provides no simple answers. It seems
see some examples. to me that you would add a configuration while
coding, not while debugging. The button with
STEPPING a gear icon (G in Figure 1) appears to duplicate
Aside from running from breakpoint to this function. Perhaps this is an undocumented/
breakpoint, the debugger also allows you to incomplete feature of IDE2 that will allow the
single step through the program, one instruction creation of threads. We can but hope.
at a time. There are a series of buttons in the
DEBUG window at the top left of the IDE (Figure
1). As we have seen the Run/Pause function is ABOUT THE AUTHORS
controlled by button K Figure 1. Aubrey Kagan has worked in electronics for more years than he cares to
Clear all the breakpoints and resume remember. He's now retired and happy to give advice where he can. He has
the execution of the user program. Place a written many articles for Circuit Cellar over the past 25 years as well as a
breakpoint at line 30. Once the program book, Excel by Example, based on three of those articles. Aubrey was one of
has halted at line 30, observe the value of the "notable contributors" interviewed in Circuit Cellar's 25th Anniversary
the variable i U t i l i t y by hovering over an issue. He's also published several design ideas and numerous blogs covering
instance in the listing. Click the step-over many aspects of electronic design. See Circuit Cellar's Article Materials and
button (button L in Figure 1). Note the five­ Resources web page for links to his publications [4][5]. He can be contacted
sided program pointer is now pointing at at akagan@sympatico.ca.
line 33. Check the value of i U t i 1 i t y now, in
CIRCUIT CELLAR • AUGUST 2023 #397

If you click (don't do it!) on the Start were already pre-defined threads listed in the
Debugging button, it invokes a second drop-down menu. Clicking the Reset Device
instance of the existing program shown button (J in Figure 1) restarts the processor
in the THREADS window of the IDE, and with a result very similar to clicking the "Start
perhaps creates a second tab of the program Debugging" button (E in Figure 1)—not what
as described above in the Start Debugging I would expect.
section. I cannot find any way of deleting the
second instance or even identifying which OTHER BUTTONS
instance is which. It may make sense if there The Restart button (P in Figure 1) seems to
reset the micro and begins execution again.
This one I understand. The Stop button (Q
v VARIABLES in Figure 1) stops the debugging process,
allowing you to edit the source file and start
_pack_size 0x0 the debug process again.
_serialPeek Oxfffffiff The right-pointing arrowhead (button H
in Figure 1) moves the cursor to the Debug
_usbConfiguration 0x0 Console. Since this version of Arduino and
_usbSetlnterface 0x0 SAMD21 processor allows for a separate USB
port, I assume that the communication with
> EndPoints: [10]
that channel would be managed in this way.
err no
g_APinDescriptioni [0] VARIABLES
We have seen that it's possible to view the
ILHflity : 0x1107 ~
contents of a variable by hovering over its
D sab e hex mode
> sercomO: {...) name. But wait, there's more! It's also possible
to view the contents in the VARIABLES window
> sercom 1:{..} Set Value (C in Figure 4). There are four categories of
> sercom2 (...) I variables, as can be seen. More advanced
Copy Vaiue
programming can investigate and even change
✓ WATCH Copy as Expression the values of the microcomputer's registers.
However, the variables that are part of the
program will appear as Local, Global, or Static,
depending on the declaration in the code.
You can expand each category to view
BREAKPOINTS □ individual variables by clicking on the right­
pointing arrowhead next to the category.
FIGURE 7
Figure 7 shows the Global variables. If
Changing the value of a variable
you scroll down the list, you'll come to our
---- 7 — M J B U U I I I I •
i U t i l i t y variable along with its current
value. You can see how many global variables
> sercom2: the compiler generates. I think I would have
• r preferred it if they were separated from the
v WATCH user variables.
If you right-click on the variable name in
the VARIABLES window, it is possible to set
the value to whatever you like. Beware: there
are no checks to prevent you from changing
the value to something illegal like a number
BREAKPOINTS greater than 65,535 for a 16-bit number.
ShowDebug.ino D lab Topics £*ebLgTo
You can view and change the value of the
variables for the other categories of variables
as well. When the program is stopped within a
FIGURE 8 function, the local variables will be accessible.
Creation of Watch Settings Of course, you can change the radix from
hex to decimal and vice versa at any time.
Additional materials from the author are available at: When entering a variable value, the debugger
www.circuitcellar.com/article-materials will accept decimal or hex (with the "Ox" prefix)
References [1] to [5] as marked in the article can be found there. without consideration of the display radix.

WATCH
RESOURCES
You can group the variables you want to
Arduino | www.arduino.ee monitor in one place, the WATCH window. To
circuitcellar.com

LCR-Reader-MPA
All-in-One Multimeter
> sercom2: (...)

WATCH

(Utility & 0x07: 0x7


(Utility: 0x1107
iUtility & OxOff 0x7

FIGURE 9
Different watch settings

add a variable, place the cursor over the right-hand side of the WATCH bar and
three buttons appear as seen in Figure 8. To add a watch, click on button X; to
collapse all, use button Y (I don't know what this means, and I don't know what it
does); and to get rid of all the watches, use button Z.
You can add more than just a variable name—you can also add an expression. For
instance, you could enter i U t i l i t y & 0x07 and just the three least significant bits
would be represented. Beware that there is no autocomplete of the variable name and
no check to see that the variable entered (which, remember, is case- and spelling­
sensitive) exists. Figure 9 shows three such expressions.

SUNDRY
There are three more windows on the left-hand side of the IDE: the CALL
STACK, CORTEX PERIPHERALS, and CORTEX REGISTERS. These are for advanced
programming well beyond the scope of this report (and my capabilities).
Most of the registers in the CORTEX REGISTERS are the same as those in the
VARIABLES | Registers section, except that in this section they are only visible
with the decimal radix— mostly. There are one or two levels that are in hex. I don't
know why.
Right-clicking on any of the window separation cross bars with the window
title, such as CALL STACK, will allow you to hide or make visible any window you
choose.

CONCLUSION LCR-Reader
Arduino IDE v2 is an ambitious project, and has made admirable progress Budget LCR Meter
toward a complete debugging environment. It will take a real project to
determine if the idiosyncrasies of the Arduino Debugger are merely annoyances
or major stumbling blocks. In either event, I believe the software could do with
more development and improvement. I hope that my article will help the
beginners amongst you to understand and use the Arduino Debugger and
introduce you to the wonders of 21st-century debugging.
12 CIRCUIT CELLAR • AUGUST 2023 #397

S
E
R
U
T
A
E
F

Embedded Linux continues to grow in popularity, with uses in every kind of application.
Given its ubiquity, the operating system (OS) must be as robust as possible, able to
reestablish itself following critical failures and malfunctions. This article discusses how
to use watchdog timers to increase the robustness of embedded-Linux-based solutions.

A mbedded Linux is becoming more and times out. To avoid rebooting, the software that
B more widely deployed in electronic devices. runs on an MCU/SoC/SiP must periodically restart
2 It's now used in almost any application this timer to its original value so it doesn't time out.
you can think of—automotive multimedia This timer restart action is called the "watchdog
systems, mobile phones, medical devices, huge feed." If the software crashes or freezes, the
servers, and household appliances, to name a few. watchdog feed is interrupted and the watchdog
As many of us are all too aware, there are many times out, causing the device to reboot. If, on the
situations—both predictable and not—that can cause other hand, everything is working as it should,
an embedded system in the field to malfunction, the watchdog feed continues uninterrupted, the
including heat exposure, electromagnetic watchdog doesn't time out, and the system doesn't
interference, severe mechanical shocks and reboot needlessly.
vibrations, and just about everything else the real The benefits are obvious. A watchdog adds
world has to offer. And of course, the embedded significant robustness to an embedded system; a
software itself on a device could contain critical device with a watchdog can, ideally, recover when
bugs. Suffice it to say there's a host of situations it crashes or freezes in the field. Without one,
that could cause an embedded device to experience human intervention is needed when devices face
critical malfunctions that lead the operating system these common malfunctions, resulting in significant
(OS) to freeze or crash. downtime and high maintenance costs.
Embedded devices must be able to recover from As dedicated hardware, watchdogs work
such malfunctions without human intervention. separately from the embedded software, enhancing
To achieve this self-sufficiency, a watchdog timer, their reliability in determining when a system
which allows a device to reboot itself in case of a needs to be reset. Watchdogs are often represented
crash or freeze, becomes a must-have resource. In as dedicated blocks in block diagrams, as seen in
this article, I discuss how to use a watchdog to make Figure 1.
embedded Linux-based solutions more robust. It's important to mention two items, here. First,
the developer must choose wisely the watchdog
WHAT ARE WATCHDOGS? timeout value. Second, watchdog feeds should be
In simple terms, a watchdog is a hardware done in the embedded software. Usually, feeds
resource in an embedded system that can be happen in routines that are called frequently, such
described as a timer with the special capability of as a super-loop. When choosing the value of the
rebooting a microcontroller (MCU), System-on-a- watchdog timeout, the developer must have a firm
Chip (SoC), or System-in-a-Package (SiP) when it understanding of how fast the embedded software
circuitcellar.com

runs. If it runs slow — perhaps because it needs HANDLING AND ENABLING


responses from slow devices (like hard disks, WATCHDOG IN EMBEDDED LINUX
some sensors, and any other high I/O w ait To enable watchdog in the embedded
operations), or because the CPU clock runs Linux, two Linux kernel configs are available:
at a low speed to save power—the watchdog
tim eout value should be high. This means • CONFIG_WATCHDOG: This must be set to Y to
in the range of hundreds of m illiseconds to allow watchdog support in embedded Linux.
seconds. If the em bedded softw are runs . CONFIG-WATCHDOG-NOWAYOUT: This config
fast, then lower tim eout values—tenths to is optional, but understanding its functionality
hundreds of m illiseconds— are used. is important when designing how the
watchdog will work with embedded Linux. It's
HARDWARE NEEDED FOR set as N by default, which means the watchdog
EMBEDDED LINUX WATCHDOGS is turned off when the application that was
To see a watchdog in action on embedded feeding it closes the file /dev/watchdog (if the
Linux, you'll need the following: application or process ends, for example). If
this config is set to Y, the watchdog keeps
• single-board com puter (SBC) that supports working (and expects feeds) even if the /dev/
em bedded Linux watchdog file is closed, forcing a reboot if the
• micro-SD card to flash the SBC embedded feed operation is interrupted for longer than
Linux image. the timeout value.
• power source to supply power to the SBC
(a 5V/2A m icro-USB power source, for Once the Linux kernel's compiled using these
example) two configs, the watchdog is now supported
by embedded Linux. The watchdog feed can be
One of the most popular SBCs available handled in embedded Linux by writing characters
is the Raspberry Pi Zero W board. It's to the /dev/watchdog file in devtmpfs. Any
significantly cheaper than the full-sized characters can be written to this file to feed the
Raspberry Pi boards, but it can run embedded watchdog, except "V". Note that the watchdog
Linux like them. Of course, if you only have feed operation only can be done as a super
a full-sized Raspberry Pi (Raspberry Pi 3 or user. Here is an example line of code to feed the
Raspberry Pi 4, for example), you can still watchdog in embedded Linux:
follow the examples described in this a rticle —
it w orks the same for all Raspberry Pi boards. sudo echo “ 1” > /d e v /w a tc h d o g

W ANU
R A I'A N I
R 'V AN2-VREF^CVREF
RA3 AN3-VREF +
R M T0CKI C1OUT
RA5 AN4SSC2OUT

RBOINT
RB1
RB2
RB3.PGM
RB4
RB5
RB6-PGC
RB7-PGD

RCOT1OSO/T1CKI
RC I T1OSI CCP2
RC2/CCP I!
RC3SCK-SCL
RC4/SDUSDA
RC5/SDO
RC6TX/CK FIGURE 1
RC7 RX DT
PIC16F873A/876A block diagram,
taken from the PIC16F87XA datasheet
(Credit: https://wwl.m icrochip.com /
MCLR V d d , VSS
downloads/en/devicedoc/39582b.pdf)
CIRCUIT CELLAR • AUGUST 2023 #397

LISTING 1
Watchdog node instructions for BCM2835 Watchdog timer
BCM2835, the SoC used in Raspberry
Pi Zero W Required properties:

- compatible : should be “brcm,bcm2835-pm-wdt”


- reg : Specifies base physical address and size of the registers.

Optional properties:

- timeout-sec : Contains the watchdog timeout in seconds

Exampl e:

watchdog {
compatible = “brcm,bcm2835-pm-wdt”;
reg = <0x7el00000 0x28>;
timeout-sec = <10>;
} 9

The developer must also keep in mind: • The OS works: The micro-SD card already
has the latest Raspberry Pi Zero W Linux
• The watchdog timeout configuration: embedded image flashed on it, and
This is configured via a device tree, since embedded Linux successfully executes
the watchdog is a hardware resource of when using this micro-SD card. I strongly
the device running embedded Linux. This recommend that you flash the image of
configuration is particular to each MCU/ Raspberry Pi OS to the micro-SD card,
SoC/SiP. It can't be changed in runtime as this is the official Linux distro for
in embedded Linux simply by writing to a Raspberry Pi Zero W (and other Raspberry
devtmpfs file; you must modify the device Pi boards as well). For more details on
tree and then recompile the Linux kernel how to flash a Raspberry Pi OS image to
to change it. In the case of the Raspberry a micro-SD card, see the Raspberry Pi link
Pi Zero W board, the instructions for its on C ir c u it C e lla r's Article Materials and
BCM2835 SoC state that watchdog time is Resources web page [1].
defined in the timeout-sec property of the • The Pi's local network access is ok: One
watchdog node in the device tree (Listing 1). of the easiest and most convenient ways
• Where to feed the watchdog: The watchdog to access the Raspberry Pi Zero W is by
feed must be done in just one process in an opening a terminal session over SSH in a
embedded Linux environment. Therefore, local network. You can use any SSH terminal
developers should carefully choose which software, like MobaXterm or PuTTY. For
process will be responsible for feeding the more information, see Circuit Cellar's Article
watchdog on its embedded Linux solution. Materials and Resources web page [2].
• When the watchdog starts: The watchdog
only starts working after opening the /dev/ In the Raspberry Pi OS, the watchdog is
watchdog file. supported by default and doesn't require any
changes in Linux kernel configs, so it doesn't
EXPERIENCING WATCHDOG IN A need a Linux kernel compilation. But if you
RASPBERRY PI ZERO W want to explore the Linux kernel configs and
Finally, let's watch a watchdog work in tweak them, I recommend the Linux kernel
embedded Linux. If you're using a Raspberry guide provided by Rapsberry Pi [3].
Pi Zero W board like I do in this article, check Having checked off those items, you're
the following before proceeding: all set to check out the watchdog at work in
your Raspberry Pi Zero W board. I'll walk you
through two examples in the remainder of this
Additional materials from the author are available at: article. In the first, we'll check that periodically
www.circuitcellar.com/article-materials feeding the watchdog prevents the board from
References [1] to [3] as marked in the article can be found there. rebooting. The second simulates a malfunction
that interrupts the watchdog feed, causing
Resources
Raspberry Pi Zero W to reset several seconds
Embarcados | www.embarcados.com.br after the interruption. In both scenarios, a shell
Raspberry Pi | www.raspberrypi.org script will be used to automatically feed the
circuitcellar.com

watchdog every second, and print a message LISTING 2


Shell script source code
on the screen indicating that the watchdog has ! / b in / b a s h
been fed. The source code for this shell script is w h ile t r u e
shown in Listing 2. do
Follow these steps to check that feeding the e c h o “ 1” > / d e v / w a t c h d o g
watchdog prevents the board from rebooting: e c h o “ W a tc h d o g i s f e d ”
s le e p 1
• Go to the home folder w ith the com m and done
cd
• Create the shell scrip t file by running the
nano f e e d _ w a t c h d o g . s h com m and. board in case of a critical failure in one of your
• Paste the source code of Listing 2 in nano applications, don't use this approach.
text editor, then save and exit (use the For critica l solutions that use em bedded
follow ing keyboard shortcu ts for this: Ctrl Linux as its OS, it's a good practice to set
+ X, Y). CONFIG_WATCHDOG_NOWAYOUT to Y. This
• Give th is shell scrip t executable perm ission ensures the w atchdog keeps w orking even if
by using the chm od +x fe e d _ the process responsible for feeding it crashes
w a t c h d o g . s h com m and. or is accidentally closed.
• Execute the f e e d _ w a t c h d o g . s h shell In the case involving both scenarios—that is,
sc rip tw ith the s u d o . / f e e d _ w a t c h d o g . a critical solution that runs on an embedded Linux
sh com m and. distro containing systemd, and you use a systemd
• Observe the watchdog being fed (and that service to feed the watchdog—it's good to use
the "W atchdog is fed" m essage is printed) the R u n tim e W a tc h d o g S e c configuration in
every second, preventing the R aspberry Pi the service file. This configuration defines the
Zero W from rebooting. maximum time allowed between the embedded
Linux boot and the first watchdog feed operation,
Easy enough! Let's move on to the second in seconds. Then, in situations where embedded
test, in w hich w e'll sim ulate a m alfunction Linux faces initialization problems and gets slow
that in terru pts the watchdog feed operation. (or unable) to boot, the embedded Linux board
The m alfunction closes the shell scrip t we will autom atically reboot.
created to sim ulate a crash in the process However, be careful when using this. If
th at's responsible fo r feeding the watchdog. R u n tim e W a tc h d o g S e c is set to a low value
This causes the R aspberry Pi Zero W board (m eaning insufficient tim e for em bedded
to reboot several seconds after the watchdog Linux to properly boot), the em bedded Linux
stops being fed. To do this: will be trapped in a boot-loop sequence, and
will be unable to boot. So if you decide to use
• Execute the feed_watchdog.sh shell scrip t R u n tim e W a tc h d o g S e c , set it to a tim e value
by using the sudo ./feed_watchdog.sh that allow s your em bedded Linux to properly
com m and. boot. As th is tim e varies from solution to
• W ait fo r a few seconds, then stop the solution, you m ust observe how much tim e the
feed_watchdog.sh shell scrip t execution em bedded Linux takes to boot to determ ine a
using the Ctrl + C keyboard shortcut. This suitable value for R u n tim e W a tc h d o g S e c .
w ill stop the watchdog feeding operations.
• A fte r several m ore seconds, the watchdog CONCLUSION
w ill tim eout, and the R aspberry Pi Zero W I hope my breakdown of how to use a watchdog
board w ill reboot. in embedded Linux helps you design more robust
solutions. With a watchdog, your embedded Linux
SOME SUGGESTIONS will be able to recover from crashes and freezes.
I suggest that you use a dedicated This capability is a requirement for critical
process (started right after boot) to feed the solutions, which makes a watchdog a must-have
watchdog. If the Linux distro you're using feature to prevent big downtimes and the need for
contains system d, you can create a service to human interventions (and related costs) to recover
execute a process (execution of a shell script, the device in the field.
for example) right after the board boot that
autom atically feeds the watchdog periodically.
Then, you don't need to change one of your ABOUT THE AUTHOR
application source codes to feed the watchdog. Pedro Bertoleti is a Brazilian embedded systems engineer and publisher
Just be aware that the watchdog will then only of a B ra zilia n em bedded system s w ebsite called Em barcados. He has
cause the board to reboot if a critical failure extensive experience in development with PIC, ESP32, ARM Cortex MO and
happens to system d (or to the whole Linux M3 microcontrollers. Bertoleti also is knowledgeable about loT projects and
em bedded system), or if the service stops
embedded Linux systems development.
for some reason. If you want to reboot the
16 CIRCUIT CELLAR • AUGUST 2023 #397

S
P a D e t e c t i o n and Detejmence
E
R
U
T
A
E
F

Raul Alvarez-Torrico

In Part 1 of this article series, I tested and reviewed Seeed


Studio's SenseCAP K1100 Kit for prototyping loT apps. This
month in Part 2, I discuss the prototype I built using a Wio
Terminal and a Vision Al Module from the kit, and an ESP32-
based audio player/web server. The system detects when my
dog tries to "mark territory" in my yard, then plays an audio
warning file of my recorded voice to try to distract the dog and
stop the behavior.

n Part 1 of this article, "Model Training To follow what will be discussed here, you
and Deployment" (C irc u it C e lla r 395, need to have some familiarity with concepts
June 2023, 2023) [1], I briefly tested such as deep-learning models, transfer
and reviewed Seeed Studio's SenseCAP learning, datasets, and model evaluation
K1100 Kit for prototyping Al-based Internet parameters. You also need to have some
of Things (loT) applications. The kit comes basic experience implementing Espressif
with a microcontroller (MCU) module, Wi-Fi/ Systems ESP32-based web servers and clients
Bluetooth/LoRa wireless communications with Arduino. To get additional background
capabilities, and a set of sensors to let you regarding the SenseCAP K1100 Kit, please
easily get started prototyping loT applications. refer to Part 1 [1].
It also comes with the Grove Vision A l
module—an Artificial Intelligence (Al) camera BLOCK DIAGRAM
for embedded, deep-learning computer Figure 1 is the block diagram for the
vision, which is particularly interesting. dog detection and deterrence system. The
The kit is advertised by the manufacturer object detection sub-system comprises the
as having a fast Artificial Intelligence loT Wio Terminal and Vision A l Module from the
(AIoT) application deployment track, great SenseCAP K1100 Kit. A detailed description
extensibility with more than 400 "Grove" of the Wio Terminal specifications was
sensors to support many application and given previously [1]. The Wio Terminal is
customization options, broad integration basically an Espressif ESP32-based controller
with cloud services, and an open-source that includes a display, some push buttons,
programming platform compatible with Bluetooth and Wi-Fi wireless connectivity,
beginner-friendly platforms such as Arduino. a micro SD card slot, a variety of onboard
I tested the kit's Vision A l module object sensors, and an I/O connection header. The
detection capabilities, along with the Wio Vision A l Module is composed of a camera
Terminal MCU module, by following the product's and a high-performance MCU designed for
documentation for training and deploying a battery-powered machine learning (ML)
custom, deep-learning model. This month in Part applications. The MCU integrates a powerful
2, I will discuss the build of my "dog detection Digital Signal Processor (DSP) core that
and deterrence" prototype. The system detects accelerates convolution operations, which are
my pet dog when he tries to mark territory near typical of neural network algorithms.
my backyard door. After the dog is detected, Every time a dog is detected in the
an audio warning with my recorded voice is camera's field of view, the Vision A l module
triggered to try to dissuade him. sends detection data in ASCII format to the
circuitcellar.com

Wio Terminal thorough an I2 C connection. It


sends, for instance, the class of the detected
object and the confidence score. Then, the
Wio Terminal sends an HTTP request to the
ESP32-based audio player/web server to play
a warning audio file to dissuade the dog. The
ESP32 board receives the HTTP request and
plays an MP3 audio file randomly selected
from a list. The MP3 files in the list contain
my recorded voice with sentences to try
to dissuade the dog. There are recorded
phrases, such as: "Hey, Rigby, what are you
doing?" "Where did you leave your angry
bird toy? Go and fetch it." "Good boy!" The
idea behind this is that when the dog hears
my voice, he will get distracted and deterred
from marking territory. Besides, I know for FIGURE 1
a fact that he never does his business when DOG DETECTION MODEL Block diagram for the dog detection
people are present. So, it's a way of fooling I followed Seeed's documentation to train and deterrence system.
him into thinking I'm nearby. the dog detection model. Details on how I did it
I stored these audio files in a local file are given in Part 1 [1], or you can refer directly
server I have at home. When the ESP32 server to the official documentation [2]. The resulting
receives the HTTP request, it randomly selects model precision wasn't very good back then,
an MP3 file URL from an array, and downloads so I re-trained the model again using more
it from the local file server. Alternatively, the pictures. Here's what I did this time:
files could be stored and retrieved from a On Roboflow's "Universe" website [3], I
micro SD card reader attached to the ESP32. created my own Roboflow project, and then
The "Arduino Audio Tools" library used to read cloned to my project all the images from the
and play the audio files supports fetching files "dogs-avxOk" dataset I used to train the
from a URL or from an SD card. In my case, I model the first time [1]. Roboflow lets you
spared the use of an additional micro SD card do that with open-source datasets on its
module, and just stored the files in my local site; you just have to create a free account.
file server. A tutorial on Roboflow's blog page explains
The ESP32-based audio player/web server how to do the cloning. (I added the link to
uses the Analog Devices MAX98357A I2 S
audio amplifier module to play audio. The
MAX98357A integrated circuit (IC) operates
with power input voltages from 2.5V to 5.5V
and delivers 3.2W output power into 40 at 5V,
with 92% efficiency. It supports sample rates
from 8kHz to 96kHz and left, right, or (left/2
+ right/2) output schemes. As a transducer
to reproduce the sound waves, I connected
a regular passive computer speaker to the
MAX98357A module's output.
The original idea was to use the Wio
Terminal also to play the audio files, but I
couldn't successfully compile the "Arduino
Audio Tools" library with SenseCAP K1100
Kit's SenseCraft source code. Apparently,
Wio Terminal's SenseCraft source code
hardware configurations clash with the
AudioTools library configurations. So, after
unsuccessfully trying to compile using
many source code configuration variations,
I decided to use an extra ESP32 board to
play the audio files. This approach added
the benefit of not having to place the audio­
playback sub-system near the object­
detection sub-system. I can install both in
different places for optimum camera/audio FIGURE 2
area coverage. mAP 0.5:0.95 vs. epoch graphs from 200 to 893 training epochs.
18 CIRCUIT CELLAR • AUGUST 2023 #397

it on Circuit Cellar's Article Materials and


Resources webpage.)
After cloning all pictures from the "dogs-
avxOk" dataset, I took 122 additional photos
of my two pet dogs (Rigby and Eileen) and
uploaded them to my Roboflow project. The
S
E idea was to improve the dataset and make
R
U
T the trained model more effective in detecting
A
E
F
especially Rigby (he's the troublesome one,
by the way!). Some of the photos had two
instances (that is, two dogs in the same
picture), and I had to annotate each picture
by hand. This is easy to do using Roboflow's
tools, but still it takes some time and patience.
In the first part of this series [1], I used
Object Recognition System ESP32 Audio Player Web Seruer "precision" as the metric to evaluate the
resulting re-trained models, because it was
FIGURE 3
conceptually more intuitive to explain and easy
Dog detection and deterrence circuit schematic. to understand. Besides, for this application, it
is more important to correctly detect a dog,
even if sometimes we fail to detect some dogs
in some photos (that's "precision"), than to
FIGURE 4
always detect every dog present in a photo
ESP32 audio player/web server.
(that's "recall").
To evaluate the re-trained models this
time, I will use another metric called "mAP
0.5:0.95," which stands for, "Mean Average
Precision over different lo ll thresholds,
from 0.5 to 0.95." And yes, that sounds
very confusing, and not intuitive at all. To
understand this metric requires a more in-
depth knowledge of object detection model
evaluation metrics in general. For example,
you must be familiar with concepts such
as precision, recall, precision-recall curve,
intersection over union, and "plain" average
precision. In case you are interested, I
included a link to a blog post explaining these
concepts on the Circuit Cellar Article Materials
and Resources webpage.
Generally, "mAP 0.5:0.95" is nowadays
the preferred metric used to evaluate object
detection models. So, this is the metric I used
to evaluate my newly trained model. In the
end, "mAP 0.5:0.95" is just a "percentage"
number that tells us how good our model is in
detecting objects.
After enhancing the dataset, I followed
the same process described in Part 1 to re­
train my model [1]. It is the same process
described in Seeed's official documentation
[2]. I trained the model seven times with 100,
200, 300, 400, 500, 600 and 1,000 epochs,
similarly to what I did in Part 1. (Note: In
machine learning, an "epoch" is used to
determine the accuracy of the model. It is a
measure of how many times the algorithm has
Click here to play an audio file and turn the LI iD on. seen the same data.) However, after training
Click here to turn the LED off. with 600 epochs, I noticed that mAP 0.5:0.95
was still increasing moderately; so, for the
FIGURE 5
next training session, I went from 600 right
Webpage served by the ESP32 web server. up to 1,000 epochs. Nevertheless, the training
circuitcellar.com

process automatically stopped at 893 epochs, because there was no further improvement in the
model. The training code is configured by default to stop the process if no further improvement
is observed in the last 100 epochs.
The mAP 0.5:0.95 versus number of training epochs from 200 to 893 epochs is shown in
Figure 2. By checking the Comma Separated Values (CSV) file generated in the training process
(which I also talked about in Part 1), I learned that the best result was observed at epoch 792.
And that's the state of the model exported as final after the training stopped. Still, as shown
in Figure 2, chart "f," the best mAP I got was less than 0.45, which is still a bit low. Obviously,
there's a lot of room for improvement.

TESTING THE AUDIO PLAYER


Figure 3 is the circuit schematic both for the ESP32-based audio player/web server and
the object recognition sub-systems. Beginning with the ESP32-based audio player/web server,
you can see that the required hardware to reproduce sound is minimal, and yet yielded
good results in my experience. To reproduce the sound waves, I used a passive 40 computer
speaker with the MAX98357A I 2 S amplifier. To my surprise, it sounded loud enough for the
purpose of this project. The IC is very small and yet provides reasonable output power. The
ESP32 audio player/web server prototype is shown in Figure 4. I'm powering the board using
a USB cell phone charger.
To play the audio files, the "AudioTools" Arduino library is used, along with the "CodexMP3Helix"
Arduino MP3 Codec library. Before attempting to compile the source code these two libraries
must first be installed. (See Circuit Cellar's Article Materials and Resources webpage for the
respective download links.) Testing the ESP32-based audio player in isolation from the rest of
the system is easy. It is recommended to test this sub-system first, before attempting to test
the object recognition one. And before compiling and flashing the code, remember to change the
following code lines with your own data:

const char* ssid = “MyWiFi”; // Your WiFi name


const char* password = “MyCatKnowsC++”; // Your WiFi password
// Static IP configuration:
IPAddress local_IP(192, 168, 0, 14); // Static IP to request from the router
IPAddress gateway(192, 168, 0, 1); // Correspond!ng gateway
IPAddress subnet(255, 255, 0, 0); // Corresponding subnet mask
IPAddress primaryDNS(8, 8, 8, 8); //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional

The "local_IP" is the static IP address you want to assign to the audio player/web server.
You must choose an IP from your router's address pool that's not reserved or used by any other
device. It is important to have the IP configured as "static," because this is the IP address that
will also be configured in the Wio Terminal's source code, so that it can successfully reach the
audio player/web server. Otherwise, the Wio Terminal will never find the ESP32 web server to
request the corresponding audio playback.
Once the circuit has been built and the code flashed to the ESP32, open a web browser and
point it to the audio player/web server's IP address. Using the above example, this address is
"192, 168, 0, 14." The webpage served by the ESP32 will look like the one shown in Figure 5.
This is a simple HTML page to test the web server functionality. By clicking on the first link, a
randomly chosen MP3 audio file will be played through the speaker, and the ESP32's built-in LED
will be turned on. By clicking on the second link, the built-in LED will be turned off. Otherwise, it
will automatically turn off once the audio file has finished playing.
Listing 1 is an excerpt of the Arduino code for the ESP32 audio player/web server. This
code is based on a straightforw ard example of an Arduino web server, plus code to read and
play MP3 audio files using the "AudioTools" Arduino library. In the listing, I omitted most
of the Wi-Fi configuration and setup, because it is a common procedure for Arduino-based
web servers.
Lines 5-8 show how I set up the list of MP3 files to be played back. I'm using just three audio
files with different messages, but more can be added. The audio files contain recorded phrases,
such as, "Hey Rigby, what are you doing?" "Go and fetch your angry bird toy," "Good boy!" and
so on. I used Audacity software to record my audio warnings with a microphone, and exported
them to MP3 format @64kbps. At that compression rate, the largest MP3 file is around 73KB, and
despite the relatively low bit rate, the final reproduced audio quality is quite good. To add more
audio files to the reproduction list, you just have to add their corresponding URLs to the array
shown in line 6. Of course, you must add the MP3 files to the local file server as well.
20 CIRCUIT CELLAR • AUGUST 2023 #397

1. #include <WiFi.h>
2. #include “AudioTools.h”
3. ^include “AudioCodecs/CodecMP3Hellx.h”
4. // ...
5. const byte url_len = 50; // At least the lenght of longest URL, plus 1
6. const char audio_fi 1e_array[]Eurl_len] = {“http://<my-fi1e-server-domain-or-ip>/talkl.mp3”,
7. “http://<my-fi1e-server-domai n-or-ip>/talk2.mp3”,
8. “http://<my-fi1e-server-domain-or-ip>/talk3.mp3”};
9. // ...
S 10. void setupO
E
R 11. {
U 12. I I . . .
T
A
E
F
13. AudioLogger::instance().begin(Serial , AudioLogger::Info);
14. auto config = i2s.defaultConfig(TX_MODE);
15. config.pin_ws = 15;
16. config.pin_bck = 14;
17. config.pin_data = 22;
18. i2s .begin(config);
19. // setup I2S based on sampling rate provided by decoder
20. dec.setNoti fyAudi oChange(i2s);
21. dec.beginO;
22. }
23.
24. void loop(){
25. WiFiCllent client = server.avai1able(); // listen for incoming clients
26.
27. if (client) { // if you get a client,
28. String currentLine = “”; // String to hold incoming data from the client
29. while (client.connected!)) { // loop while the client’s connected
30. if (client.avai1able()) { // if there’s bytes to read from the client,
31. char c = client. read(); // read a byte, then
32. Seri al.write(c); // print it out the serial monitor
33. if (c == *\n’) { // if the byte is a newline character
34. if (currentLine.1ength() == 0) { // Send HTTP header
35. client.println(“HTTP/1.1 200 OK”);
36. client.pri ntln(“Content-type:text/html”); client.println();
37. // Simple web page to test the server:
38. client.print(“Click <a href=\”/play\”>here</a> to play audio.<br>”);
39. client.println(“Click <a href=\”/led_off\”>here</a> to turn the LED off.<br>”);
40. break; // break out of the while loop
41. } else { currentLine = “”; }
42. } else if (c != *\r’) { currentLine += c; }
43.
44. // Check to see if the client request was “GET /play” or “GET /led_off”:
45. if (currentLine.endsWith(“GET /play”)) {
46. digita1Write(LED_BUILTIN, HIGH); // GET /play turns the LED on and plays an audio file
47. if(1is_playing) { // Only play a new audio file if there’s no other currently playing
48. is_playing = true;
49. unsigned 1nt file_index = random(0, num_audio_fi1es); // Randomly get an audio file index
50. url.begin(audio_file_array[file_index], “audio/mp3”);
51. }
52. }
53. if (currentLine.endsWith(“GET /led_off”)) {
54. digitaiWrite(LED—BUILTIN, LOW); // GET /led_off turns the LED off
55. }
56. }
57. }
58. client.stop(); // Close connection
59. Seri al .println(“Client Disconnected.”);
60. }
61.
62. copier.copy(); // Get more audio data from audio file
63. int avail = copier.avai1able();
64. if (avail == 0) { // The end of the audio file has been reached
65. is_playing = false;
66. digitaiWrite(LED—BUILTIN, LOW);
67. }
68. }

LISTING 1
Arduino code for the ESP32 audio player/web server.
circuitcellar.com

Lines 13-21 show how to configure the


operation of the MAX98357A IC with the
"AudioTools" library. Lines 15-17 in particular
configure the ESP32 pins that will be used to
do the I 2 S interfacing. These are the same pins
shown in the circuit schematic in Figure 3.
Lines 24-68 show the program's main
infinite loop. This web server implementation
is mostly a copy of the "SimpleWiFiServer"
that is included in the "WiFi" ESP32 Arduino
library, which is installed along with the
"Arduino-ESP32" board support package (see
Circuit Cellar's Article Materials and Resources
webpage). So, I won't explain in detail how
the HTTP server works. Please check the
aforementioned "SimpleWiFiServer" to see
basic details about how the web server works.
Going forward, lines 35-36 send the
response HTTP header to the web client that
originated the request. Lines 38-39 send the FIGURE 6

HTML code for the webpage shown in Figure Object detection sub-system.

5. Lines 45-55 catch the HTTP GET request


received from the webpage, each time any of
the two links are clicked. If a "GET /play" HTTP
request is received (lines 45-52), a random
index number ("file_index") is generated in
line 49 to index into the "audio_file_array"
defined in lines 6-8.
Then, the AudioTools url.begin() function is
called to request the randomly selected audio seeea studio
file from the local file server (see line 50).
The first argument to this function is a string
containing the audio file's URL. The second
argument is just the file type ("audio/mp3")
to make the appropriate HTTP request to the
local file server. The audio file in question will
be downloaded by this function from the local
file server, and played back. The Wio Terminal
will send this exact type of request every time
a dog is detected.
In contrast, if the "GET/led_off" HTTP
request is received (lines 53-55), the
built-in LED is turned off. This part of
the implementation is just for debugging
purposes, and is not required for the project's confidence:61
main functionality. Because downloading the Time consuming: 798
MP3 file completely is not required to start
Number of dogs: 1
reproducing it, line 62 is used to get additional
data bytes from the incoming MP3 stream to result:detected
continue the reproduction. Once there are no Detecting and calculating: 1
more incoming data bytes, the reproduction confidence:66
will stop automatically. Lines 63-67 let us Time consuming: 769
verify this condition and flag appropriately
Number of dogs: 1
that the audio file playing has ended.
result:detected
TESTING THE DOG DETECTION Detecting and calculating: 1
To test the trained machine learning confidence:77
model, the "UF2" model file resulting from
the training process must be flashed to the Q Autoscroll □ Show timestamp Both Ni & CR v 115200 baud v clear output
Vision Al module [1]. To do this, connect the
module to the computer with a USB cable. It FIGURE 7
will get enumerated by the operating system Vision Al detection in a web browser.
CIRCUIT CELLAR • AUGUST 2023 #397

1. void loopO {
2. i f (state == 1) {
3. uint32_t tic k = m illis O ;
4. i f ( a i . invoke()) { // begin invoke
5. while (1) { // Wait until invoke is finished
6. CMD_STATE_T ret = a i.s t a t e d ;
7. i f (re t == CMD_STATE_IDLE) { break; }
8. delay(20);
9. }
10.
11. uint8_t len = a i . g e t_re su lt_le n () ; // Receive # of detections
12. i f (len) {
13. d ig itaiW rite(LED , HIGH); // Turn external LED on
14. Send_Request(); // Send HTTP GET request to web server
15.
16. in t timel = mil 1i s ( ) - t ic k ;
17. Serial .p r in t ( “Time elapsed: “ ); S e r ia l.p r in t ln (t im e l);
18. Seri a l . p r in t (“ Number of dogs: “ ); Seri a l . p r in tln (1en);
19. object_detection_t data; // Get data
20.
21. for (in t i = 0 ; i < len; i++) {
22. Serial .p r in t in (“ re su ltd e te cte d ” ) ;
23. Seri a l . p r in t (“ Detect!ng and calcu latin g : “ ); Seri a l . p rin tln (i+ 1 );
24. a i . g e t_ r e s u lt (i, ( uint8_t*)&data, size o f(o b je ct_d e te ctio n _t)); // Get resu lt
25.
26. S e r ia l.p r in t ( “ confidence:” ); Seri a l.p rin tln (d a ta .co n fid e n ce );
27. }
28. }
29. else {
30. S e r ia l.p r in t ln (“ No id e n tific a tio n ” ); digita 1W rite( LED, LOW); // Turn external LED off
31. }
32. }
33. else {
34. de1ay(1000); S e r ia l.p r in t ln (“ Invoke F a ile d .” );
35. }
36. }
37. el se { state == 0; }
38. }

40. void Send_Request() {


41. Seri a l . p r in t (“ Connect!ng to “ ); S e r ia l.p r in tln (h o s t );
42. // Use Wi FiC lle n t class to create TCP connections
43. WiFi Client c lie n t;
44. i f ( !clien t.co n n ect(h o st, port)) {
45. Seri a l . p rin tln ( “ Connect!on f a ile d .” ) ;
46. Seri a l . p rin tln ( “Waiting 2 seconds before r e t r y in g ...” );
47. delay(2000);
48. return;
49. }
50. c lie n t .p r in t ( “ GET /play HTTP/1. l\n \n ” ) ; // Send HTTP GET request
51.
52. // Wait for the se rve r’ s reply to become available
53. in t maxloops = 0;
54. while ( ! cl le n t. aval 1a b le () && maxloops < 1000) {
55. maxloops++; d e la y (l); // Delay 1 msec
56. }
57. i f ( c lie n t . avai1a b le () > 0) {
58. String lin e = c lie n t . readString(); // Read the server response
59. Seri a l . p rin tln (1in e );
60. } else {
61. Seri a l . p r in tln (“ c lie n t . avai1a b le () timed out “ );
62. }
63. Seri a l . p rin tln ( “ Closing connection.” ) ;
64. c lie n t.s to p ();
65. }

LISTING 2
Arduino code for the object detection sub-system's Wio Terminal.
circuitcellar.com

as if it were a USB flash drive. Copy the file to the module the how easily and reliably it would perform object detection
same way you copy files to a USB drive. After the Vision A l is using the SenseCAP K1100 Kit—specifically with the Vision
loaded with the model file, disconnect it from the computer A l module and the Wio Terminal controller. Training and
and attach it to the Grove port in the Wio Terminal. The circuit deploying models with the Vision A l module is indeed
schematic for the object detection sub-system is shown in very easy. Moreover, the Wio Terminal is a great all-in-
Figure 3, and Figure 6 is a photo of the object detection one controller that embeds a relatively powerful MCU with
sub-system with the Vision A l and an external LED module wireless connectivity, an LCD screen, push buttons, and some
attached to the Wio Terminal controller. Here, I'm using onboard devices, such as an accelerometer, microphone,
another USB cell phone charger to power up the sub-system. speaker, micro SD card slot, and a 40-pin GPIO header, for
Next, connect the Wio Terminal to the PC and flash the connecting even more off-board sensors and actuators.
"object_detection_wifi_client.ino" Arduino code. A download To obtain good performance from object detection with
link to all source files is available on the Circuit Cellar Article the Vision A l module, it is critical to train the machine learning
Code and Files webpage. Before flashing the code, be sure to model appropriately. And that's the most time-consuming
change the following lines in the source code with your own and relatively hard part, since it is generally true with most
information: machine learning applications. Normally, obtaining a good
model requires crafting a very good dataset and training
c o n s t char* s s ld = “ MyW iFi” ; // Your WIFI name the model many times with many parameter variations,
c o n s t char* password = “ MyCatKnowsC++” ; until good precision is obtained. Apparently, this gets harder
// Your WiFi password when the final model will be integer-quantized and run on
c o n s t char* h ost = “ 192.168.0.14” ; an MCU. To be able to get a good model in this context,
// audio player-w eb s e r v e r ’ s IP A ddress reasonable experience and practice in model training is
normally required.
The "host" address above is the static IP address assigned It is pretty amazing what can be done these days with
previously to the ESP32-based audio player/web server. After machine vision, microcontrollers and wireless
flashing the code, open the serial terminal window in the communication. A couple of decades ago, I managed to send
Arduino IDE to see the debugging messages from the Wio some UDP packets from a Microchip PIC16F876 MCU to a
Terminal. It will try to connect to the Wi-Fi router, receive web server, using a 1" dial-up modem. Seeing that work was
detection data from the Vision A l module, and request to the mesmerizing. If someone had told me what would be
ESP32 web server that an audio file is played every time a possible to do two decades later with a microcontroller, a
dog is detected. tiny video camera, and wireless communication, I would have
For debugging purposes the Vision A l module can be not believed it!
connected to a PC with a USB cable as well, to monitor
the detection process on a web browser [1]. Figure 7 is a
screenshot of how it looks. The text in the lower section is ABOUT THE AUTHOR
from the Arduino IDE's serial terminal, which shows the Wio Raul Alvarez-Torrico has a BEng in electronics and is
Terminal's output. the founder of TecBolivia, a company offering services in
The Arduino code for the Wio Terminal previously discussed physical computing and educational robotics in Bolivia.
in Part 1 of this article [1] is given in Listing 2. Most of the code In his spare time, he likes to experiment with wireless
is an adaptation from the "object_detection" example that sensor networks, robotics, and artificial intelligence.
comes with the "Seeed_Arduino_GroveAI" library installation.
He is also committed to publishing articles and video
I just added web client capabilities to send HTTP requests to
tutorials about embedded systems and programming
the ESP32 audio player/web server.
in his native language (Spanish), at their company's site
When the system detects a dog, it turns on the external
www.TecBolivia.com. You may contact him at raul@
LED connected to the Wio Terminal GPIO header. Then, the
tecbolivia.com.
Wio Terminal sends an HTTP GET request to the ESP32 audio
player/web server to play an audio file (see lines 13-14). The
ESP32 receives the request, selects an audio file, and plays it
through the MAX98357A I2 S audio amplifier.
Lines 40-65 contain the Send_Request() function definition Additional materials from the author are available at:
that sends the HTTP GET requests. If you have previous www.circuitcellar.com/article-materials
experience implementing HTTP servers and clients with the References [1] to [3] as marked in the article can be found
Arduino platform, you will not notice anything unusual or there.
complicated in this function. The function basically sends the
request and prints the server's response to the serial terminal. RESOURCES
Note that line 50 is in charge of sending the "GET /play" request.
Arduino | arduino.cc
As you may recall from Listing 1, the "/play" Uniform Resource
Identifier (URI) is the one that triggers the reproduction of an DFRobot | www.dfrobot.com
MP3 audio file on the ESP32 server. You can confirm this by Espressif Systems | www.espressif.com
referring again to lines 45-52 from Listing 1.
Roboflow | www.roboflow.com

CONCLUSION Seeed Studio | www.seeedstudio.com


The main purpose of building this prototype was to see Ultralytics | ultralytics.com
24 CIRCUIT CELLAR • AUGUST 2023 #397

4 II II

By
Michael Lynes

E
R
U
T
A
E
F
H
C
E
T

responding to your commands and went


DRONE WARS rogue, flying on and forcing you to chase it
A long time ago...in a laboratory far, far while its FPV camera kept displaying the name
away... of the infamous OG-EE, Obi-wan Lyne-nobi?"
I was sitting at my lab bench, deep in I paused for a beat, letting his words settle
thought, running the sequential transitions of into my awareness, and then, following the
my latest state machine control loop through promptings of my ancient discipline, I raised
my mind, when I felt a sudden stirring in my gaze, meeting his eyes.
the Force. I glanced up through the haze of "Obi-wan, hmm. That's a name I haven't
solder smoke rising above my prototype as a heard in a long time, a long time. You thought
young digital data engineer (DDE) stumbled he was dead? No, he's not dead. . .not yet.
in, looking a bit disheveled and out of breath, Take you to him? Well, that's easy, he's me!" I
his hands full of blinking equipment. paused again, smiling at his wide-eyed look.
"Sit! Sit!" I said, laying my 10X probe down "Don't look so surprised. I haven't gone by
and gesturing to the rolling chair beside me as the name Obi-wan since, oh, since before
I pushed my ancient oscilloscope to the side. you were born. A drone, though? I can't say
I watched in silence as he placed his burden I remember ever owning a drone." I laughed
on the bench, a sigh escaping his lips as he as his face fell, and then took pity on him
massaged his hands. "There, that's better," once more. "No worries! It just so happens
I continued, giving him a friendly smile, "You that my current project has led me to do a
look a little shaken up. And as we all know, lot of research on this subject. So, grab a
the blazing hot August sands of the Jungian midichlorian-laced energy drink, plug your
Wasteland are not to be traveled lightly." He drone battery into the charger next to that
glanced in my direction, a puzzled look on his power strip, and sit back and listen while I
face as he opened his mouth to reply, but I did expound."
not give him a chance to interject.
"So, my young DDE, what brings you out HISTORY
this far?" I asked, nodding politely as he Given that hopefully entertaining
began to relate his wandering tale. At last, his introduction, let me slip out of my Jedi robes
flow of words wound down into silence, and I and begin this missive with some history.
looked up, noting his slightly lost expression. Just like me, drones, a.k.a. Unmanned Aerial
"Well, that's quite a story!" I said, Vehicles (UAVs), have been around for a lo-
"Following a lost droid, did you say? No? Ah, o-o-ng time, and over the years they have
a drone! What's that? You say it stopped changed a lot. The drones we are all familiar
circuitcellar.com 25

with— battery-powered, multi-rotor copters


with RF remote control, 4k HD streaming
cameras, and GPS-guided autonomous flight
capabilities—are the most recent generation
of UAVs. The origin of these flying craft goes
back to the end of World War I—that is, if you
restrict your definition to vehicles that operate
under powered flight. There is an argument to
be made however that the unmanned hot air
balloons used by the Austrian army to deliver
explosive charges within the city walls during
their 1849 attack on Venice would also qualify
as UAVs.
As you can see in Figure 1, one of the
driving forces behind UAV development over
the past hundred years has been their utility
in armed conflict. The advantages of using a website entitled the "A Not-So-Short History military operations. (Source:
UAV during battle are obvious. Attacks can be of Unmanned Aerial Vehicles" [3]. There, they University of Albany [1]) T
E
C
carried out on remote enemy positions with trace the origin of this technology back to 1783, H
more precision than contemporary artillery, the year that the French innovators Joseph- F
E
A
and without risking the lives of human pilots Michael and Jacques-Etienne Montgolfier flew T
U
to do so. Also, the loss of a UAV has little cost a hot air balloon of their own design in the R
E
to morale, while the damage done to the first-ever public demonstration of unmanned
enemy can be significant. aircraft.
In line with their focus on wartime Figure 2 provides a neat graphical
applications, the webpage of the British representation of the different modern form
Imperial War Museum [2] has an excellent factors for various autonomous and semi-
write-up on the military history of drones. autonomous drones. And, lastly, Wikipedia
As you can read there, the infamous "buzz has a short overview of the "flight stack,"
bombs" that were used by the Germans during the firmware application at the core of every
the Blitz of London were a type of crude UAV, modern UAV [5].
and, though their primitive guidance systems Regarding the embedded control
made them far less effective as compared application, there are three main real-time
to conventional high-altitude bombers, the components to the flight stack, arranged
psychological effect was profound. in order such that the most time-critical
Consortiq, a consulting group that tasks are lower and closer to the hardware
specializes in helping their customers develop sensors, battery monitor, and motor controls
efficient, simple, and effective ways to use (Figure 3). Let's take a quick look at each of
UAVs (more about them and their business these.

FIGURE 2
Some UAV Form Factors (Source:
The Multidisciplinary Digital
Publishing Institute MDPI [4])
26 CIRCUIT CELLAR • AUGUST 2023 #397

Attitude Control: The attitude control section, meaning


the algorithm that reacts to changes in the spatial orientation
of the UAV (Figure 5) is typically the most time-critical. The
aircraft must sense and react to external forces, maintain
level flight, and potentially modify certain control structures
in real time to sense and avoid obstacles.
Velocity Control: The second most time-critical section
is velocity control. Depending on the complexity of this
subsystem, the UAV may be able to sense its airspeed and
groundspeed, as well as attain and maintain a set velocity, or
a desired climb or descent rate, in the presence of adverse or
favorable winds aloft.
Position Control: The least time-sensitive subsystem in
the flight stack is position control. This subsystem can include
GPS sensors and interfaces, radio ranging altimeters, and
Attitude and Heading Reference System (AHARS) devices, all
used to keep the UAV on course and at the proper altitude.
E This subsystem may interact directly with the user interface,
R providing feedback to the operator regarding the status of
U
T
A FIGURE 3 the UAV, and allowing the operator to fly the instrument
E
F UAV flight stack block diagram remotely much as they might as a pilot in command of a
H
C manned aircraft.
E Perpendicular axis
T Many companies make flight stack software, and these
days it is not worth the effort to "roll your own." Later in this
article, we'll discuss some of the best providers of this UAV
component.
Speaking of components—modern UAVs have a lot of them.
Figure 5 shows the basic hardware subsystems of a typical
UAV, arranged in an exploded view. In this type of quad­
copter form factor, there are four rotor blades, constructed
of either high-impact plastic or carbon fiber impregnated
with resin. Also shown in this view are the four DC motors
along with their associated speed controller boards, as
well as the embedded flight controller main board and the
power distribution board. All the components are mounted
to the UAV airframe, typically made of plastic or carbon fiber,
along with the battery. The total weight of all components is
Lateral axis minimized as much as possible. The power-to-weight ratio is
Pitch an important factor that determines how long/fast/high the
drone can go before its power source is depleted and it must
FIGURE 4
return to base.
Flight Control Vectors
The antenna, control receiver, and First Person View
(FPV) transmitter all work together to receive command
information from your phone-based or stand-alone controller,
as well as send back images and status data over the same
wireless link. The RF transmission power, as well as the uplink
and downlink speeds, are typically asymmetrical as far more
bandwidth and signal strength is required for the downlink
channel (UAV-to-controller), than for the uplink direction.
As a side note, the world of drones comes with a whole
bunch of new (to me) jargon and acronyms. To understand
what enthusiasts mean when they refer to FPV (First Person
View), ARF (Almost Ready to Fly), or CoG (Center of Gravity)
I found a good resource dictionary on Oscar Liang's hobbyist
website [7]. Oscar also has a lot of tutorials on how to build
your own FPV drone [8].

MARKET PLAYERS
As mentioned above, the world of UAV drones is vast.
The UAV market has exploded in popularity, and the number
FIGURE 5
and types of drones have kept pace. You can find extremely
UAV Components arranged in an exploded view (Source: Ebrary [6]) inexpensive off-the-shelf drone systems sold as toys in
circuitcellar.com

almost any store, with semi-autonomous of UAVs for use in many types of industries—
operation, automatic leveling, return-to- everything from full-scale enterprises like
home (RTH) capability, and even built-in Amazon and Walmart to SMEs like Grub Hub
cameras. and Zipline.
Forcel RC: The company Forcel RC [9], Allerin: Allerin is a software solution
in business since 2012, has a full line of RC provider that specializes in Internet-of-Things
toys, with several types of drones in stock. (loT), blockchain, data sciences, and artificial
For less than twenty dollars you can purchase intelligence (Al). It has several offerings in
the Forcel Scoot, a mini drone that can hover, the loT-UAV crossover space, developing
avoid obstacles, soft land, and respond to sophisticated networked applications to
either RF or hand gesture commands. For run on and control UAV devices. On Allerin's
under $100, it also has the Blue Heron and website I found a list of UAV applications
Blue Jay, larger toy drones with cameras, live
streaming video, 120-degree FPV capability,
and long-lasting lightweight lithium batteries.
The next rung above the toy drones is
the hobbyist-level UAVs, ranging in price
from around $200 up to about $1,500. These
devices are available from a huge number of
suppliers, though there are a small number
of industry leaders such as DJI [10] and Autel
Robotics [11].
DJI: I found a PC Magazine article listing
the best drones of 2023, many of which were
either the DJI or the Autel Robotics brand
[12]. In the "Creators on a Budget" category,
I found the DJI Mini-3 (Figure 6). This drone
is about $400 complete and comes with
extended battery life, 4K HDR video, digital
zoom, GPS navigation, 32Gb of onboard flash
storage, and a 10-km controlled flight range.
This device, along with many others, can be
flown using the DJI Universal Drone Controller
in combination with your Android or iOS­
based smartphone. The controller itself has
a large battery pack and can last up to six
hours between charges, even while providing
power to your smartphone.
DJI also has high-end drones for
photography, such as the Air 2S model.
Priced at just over $1,000, this is a folding
FIGURE 6
quad-prop UAV, with a built-in 3-axis gimbal-
DJI M ini-3
stabilized 5.4k streaming video camera,
obstacle sensing, a 256Gb storage card, and a
31-minute flight time.
Autel Robotics: Autel Robotics has a wide
range of UAV offerings. The EVO Lite+ seen
in Figure 7 is a long-range UAV that comes
equipped with a one-inch CMOS sensor that
has been optimized to film in low light,
moonlight, or nighttime conditions. Costing
just under $1,500, this model can provide
6k/30FPS streaming video, 20-megapixel still
photos, and up to 24km of flight range. Autel
has many other UAVs as well. On its website
the company acknowledges that DJI is the
true market leader, so it tries to differentiate
itself on features and specialized applications.

APPLICATIONS
Speaking of applications: The popularity FIGURE 7
of UAV for hobbyists has led to the adoption Autel EVO Lite+
CIRCUIT CELLAR • AUGUST 2023 #397

(Figure 8) for various industries [13]. Some while avoiding other aircraft, people, pets,
of those listed are: and obstacles.
• Geographic and archeological mapping—
• Aerial photography—Airborne Studios: Lidar USA worked with Josh
Lidar USA:
Founded in 2017 by Eddie Graham and Gates of Expedition Unknown to make a
Brandon Hower, the company bills itself 3D map of the lost city of El Mirador using
as "drone camera experts," listing Exxon their UAV-mounted Snoopy HD-LiDAR. Over
Mobile, the band Leonard Skynyrd, and the course of two weeks, they created a
the New York Stock Exchange among their bare-earth model of the Pyramid despite
clients. the dense jungle vegetation that covered
• Shipping and delivery—Amazon: The the site.
largest online retailer in the world is • Search and rescue—DSLRPros: founded in
building a massive drone fleet to accomplish 2012 by filmmaking enthusiasts, DSLRPros
its goal of creating a sophisticated sense- specializes in search and rescue (SAR)
and-avoid system that will enable drone- drones and related technologies. They can
powered deliveries at greater distances provide cost-effective FLIR thermal UAVs
that can be deployed in minutes.
• Agriculture— The University o f Florida:
IFAS extension provides guidance to
farmers in the use of drones for precision
agricultural spraying, surveying of crops,
and photogrammetry to measure crop
growth and harvesting criteria. Various
technologies, including IR imaging, hyper-
spectral analysis, and laser-reflected
imaging are used.

Consortiq:Consortiq, mentioned above,


provides consulting services for industries
that want to explore the use of UAV tech.
Originally founded as the company Cloud
12 in 2012, their initial focus was helping
the film and video industry transition from
manned aircraft for aerial shots to UAVs.
Since then, they've expanded to training
various industries on UAV technology,
including oil and gas mining concerns, live
broadcasting and news organizations, electric
power generation companies, NASA drone
pilots, and wireless phone providers such as
Verizon. They also have trained operators of
specialized UAVs for delivering critical medical
supplies to remote areas. To date, they have
trained over 1,800 candidates on UAV tech,
and they're a good resource partner to look
up if you need information on using UAVs in
Figure 8
your specific industry.
UAV Applications (Source: Allerin)

Additional materials from the author are available at: www.circuitcellar.com/article-materials


References [1] to [18] as marked in the article can be found there.

Resources
Airborne Studios | airborn-studios.com DSLRPros | www.dslrpros.com

Allerin | www.allerin.com Forcel RC | forcelrc.com

Autel Robotics | www.autelrobotics.com HolyBro | holybro.com

Chetu | www.chetu.com Lidar USA | www.lidarusa.com

Consortiq | consortiq.com Modal Al | www.modalai.com

DJI | www.dji.com NXP | www.nxp.com


circuitcellar.com 29

ROLLING YOUR OWN DRONE


Last but not least are the many UAV DIY
kits that are available today. Building and
customizing your own drone has never been
easier, with many companies large and small
providing UAV components for the drone
builder. As previously mentioned, Oscar
Liang's fine website has a comprehensive
explanation of his own bespoke FPV drone
build. As seen in Figure 9, Oscar's tutorial
gives the finer points of drone fabrication,
including parts lists, a wiring and assembly
guide, detailed fabrication tips, a firmware
programming guide, and insider tips and
tricks to help the reader have a satisfactory
drone building experience. Please note that
this is an advanced project, but still well within
the skill set of most Circuit Cellar readers. T
E
C
Modal A l: Based in San Diego California, H
Modal A l was spun out of Qualcomm in 2018. F
E
A
Modal specializes in Al-enabled flight stacks FIGURE 9 T
U
and control platforms. Its VoXL line of drone in world-class software solutions, including DIY Droning R
E
development kits and tools, combined with full-featured drone software development
their Blue UAS Framework environment, kits [16]. It provides SME and enterprise­
provides a powerful customizable platform for class drone management software solutions
advanced drone research and development based on popular drone adapters, payload
[14]. Modal also provides design and consulting managers, connectivity managers, and APIs.
services, helping you realize your vision and Developers can also purchase and leverage
grow your in-house drone expertise. For UAS their off-the-shelf toolkits and framework
Autopilot software development it has the PX4 packages for their UAS/UAV implementation
open-source flight core that can be paired projects.
with VOXL for obstacle avoidance and indoor NXP: NXP also has a presence in the UAV
or outdoor GPS-denied navigation [15]. Flight space with their HoverGames drone kit [17].
Core can also be used independently as a As outlined in Figure 10, this kit features the
standalone, high-performance, secure flight mechanical, electrical, and other components
controller. needed to evaluate the RDDRONE-
Chetu: Chetu is a software development FMUK66 drone, adding BLDC motor control
consultant partner with over 2,800 in-house capabilities, and a platform to which it can
development personnel. Chetu specializes be mounted. Designed with the HoverGames

NXP Included in K i Included tn Krt Required. Not included Optional Not included FIGURE 10
NXP HoverGames kit block diagram
30 CIRCUIT CELLAR • AUGUST 2023 #397

FIGURE 11
PX4 Vision Dev Kit

E
R
U
T
A
E
F
H
C
E
T

coding challenges in mind, it is to be noted "Yes, I will be coming with you. It's getting
that the kit is intended for the professional late, and though the sand people are easily
developer and does not include software. This frightened, they will be back, and in greater
NXP hardware package will work with popular numbers. I think I should come along and
third-party software stacks, like the PX4 from see you safely back to your cubicle." I paused
Modal A l mentioned earlier. for a moment, holding the lab door open and
HolyBro: HolyBro is a multivendor allowing my grin to show.
distributor of drone components, including "I like you, young DDE, and I can sense
development kits from most major vendors your potential. It's time you learned the ways
[18]. They have many of the PX4 development of the Force, if you are to become a Jedi like
kits in stock (Figure 11). The popular PX4 your father before you." Without a backward
Vision kit is available from them for under glance, I strode out the door, smiling at his
$2,000. belated laughter as he, at last, got the joke.

ESCAPING TATOOINE CONCLUSION


"So," I said, looking up and catching his All kidding aside, UAV technology, and its
eye, "That's enough talking from me. You associated impact on our society, is still in its
look a bit tired, and I can see that your drone early stages. The confluence of drones, robotics,
battery is fully charged." I watched his face, and artificial intelligence is already producing
noting his confusion as I folded his drone breathtaking advances on multiple fronts, too
in one smooth motion and stood, gesturing many in fact to delve into in this one article. I
toward the door of the lab. find the topic fascinating, and I hope you do as
"Gather the rest of your equipment, we well. As always, this is only one old Jedi's
should be going." I smiled inwardly, and then opinion. You should do your own research, and
continued answering his unspoken question, may the Force be with you...always.

A B O U T THE AUTHOR

M ichael Lynes is an entrepreneur who has founded several startup ventures. He was 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
4
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
Stories, and another collection called Novem ber Tales, inspired by the fiction of Ray Bradbury. He cu rrently lives w ith his w ife
M argaret in the beautiful, secluded hills of Sussex County, New Jersey. You can contact him via em ail at m ikelynes@ gm ail.com .
NEXT-GENERATION MCUs FOR
A RANGE OF MOTOR SYSTEMS
Optimized performance, size and peripheral functions
for single motor control and inverter applications
32 CIRCUIT CELLAR • AUMfeT 2023 #397

Datasheet:
Application-Specific MCUs

By
Sam Wallace,
Editor-in-Chief

While the general-purpose microcontroller (MCU) isn't going anywhere


anytime soon, this month's gallery of nine new application-specific MCUs
demonstrates that building for hyper-specific solutions continues to be an
active, diverse, and broad area of MCU design.

icrocontrollers (MCUs) geared functionality. Overall, there has been a lot of


1 ■ toward specific industries and movement and evolution in multiple directions
1 W markets are not a new concept. in the world of MCUs built for hyper-specific
Aside from general-purpose MCUs, needs. As many readers are aware and as this
there are MCUs designed for broad swaths of column will make plain, automotive MCUs are a
industry, such as automotive, industrial, and very active sector within this category.
wireless MCUs. Over the last few years, we've Application-specific MCUs are often most
seen an increase in further specialized MCU practical (and most widely deployed) in high-
designs that come with tailored feature sets volume use cases like motor control, as many
aimed at specific application needs. These of the intended applications in the following
application-specific MCUs provide developers gallery pages illustrate. You'll find products
of embedded systems with solutions that are built for wearable devices, designed for power
just the right size: complete with feature sets, delivery inside vehicle cabins, or geared
packaging, and/or performance levels that fit toward low-power cellular applications. Our
their system requirements. gallery features MCUs, system-on-chips (SoCs),
This was originally primarily seen in 32- and system-in-packages (SiPs) for everything
bit MCUs—and indeed, at least a couple such from smart sensor networks, to high-quality
products pop up in this month's gallery. But audio, to digital signal control, to software-
these days, even 8-bit MCUs are finding use defined vehicles. The array of specific
in application-specific solutions (such as this applications is, of course, endless, so naturally
month's automotive offering from Microchip this gallery of nine products represents only a
Technology). Meanwhile, 32-bit MCUs are small sampling of recent releases from MCU
incorporating Al capabilities along with loT manufacturers.

• NEXT MONTH'S TOPIC: Power/Battery Management Send related product announcements to editor@circuitcellar.com
circuitcellar.com 33

Ultra-Low-Power 32-Bit MCU Highly Integrated In-Car Automotive Interface MCU


for Wearable Devices Power Delivery with Many Peripherals D
A
T
A
Analog Device's MAX32660 is an Infineon's EZ-PD CCG7D is a dual­ The PIC18-Q84 fa m ily o f 8 -b it S
H
ultra-low -pow er, cost-effective, highly- port USB-C power delivery (PD) solution MCUs combine a wide range o f Core E
E
integrated 32-bit m icrocontroller that comes with an integrated buck­ Independent Peripherals (CIPs) w ith T

designed fo r battery-pow ered devices boost controller for charging applications C ontroller Area N etw ork Flexible Data
and wireless sensors. I t combines a in cars. Compliant with the latest USB Rate (CAN-FD) fo r autom otive interface
flexible and versatile power m anagement Type-C and PD specifications and AEC and sm a rt sensor netw orks. The Q84 is
unit w ith the powerful Arm Cortex-M4 Q-100-qualified, the CCG7D is designed the firs t 8 -b it MCU w ith CAN-FD. W ith
processor w ith floating point unit (FPU) for automotive applications that support up to 128KB Flash m em ory and up to
in the industry's smallest form factor: Display Port (DP) in alternate mode. It's 48 pins, these cost-efficient MCUs bring
1.6mm x 1.6mm, 16-bum p WLP or 4m m particularly suited for applications such new peripherals like the custom izable
x 4m m , 20-pin TQFN-EP, or 3m m x 3m m , as head unit chargers, rear seat chargers, Universal T im er (UTMR), and context­
24-pin TQFN-EP. The MAX32660 enables and rear seat entertainm ent systems. sw itching capability to the 12-bit ADC
designs w ith complex sensor processing w ith com putation fo r autom ating
w ith o u t com prom ising b a tte ry life. I t • USB-PD: Supports two USB-PD ports; analog signal analysis fo r re a l-tim e
also offers legacy designs an easy and Supports USB-PD revision 3.1 including system response. Microchip offers full
cost-optim al upgrade path from 8- or programmable power supply (PPS) functional safety packages fo r ISO
16-bit m icrocontrollers. mode; Extended data messaging 26262 and SGS TUV Saar ASIL B which
• Type-C: Configurable resistors RP and includes the FMEDA, safety manual and
• In te rn a l oscillator operates up to RD; VBUS provider NFET gate driver; diagnostic lib ra ry fo r the Q84 fam ilies.
96MHz Integrated 100-mW VCONN power supply
• 256KB Flash m em ory and control • 64MHz internal oscillator
• 96KB SRAM, optionally preserved in • 2x Buck-boost controller • Up to 13KB data SRAM and IK Data
lowest power backup mode • 2x Legacy/proprietary charging blocks EEPROM
• 16KB In s tru c tio n Cache • System-level fault protection • 12-bit ADC w ith Com putation and
• M em ory Protection Unit (MPU) • 32-bit MCU subsystem: 48-MHz Arm context sw itching, up to 43 channels
• Low 1.1V VCORE supply voltage Cortex-MO CPU, 128-KB Flash, 16-KB • Two 1 6 -b it Universal Tim ers (UTMRs)
• 3.6V GPIO operating range SRAM, 32-KB ROM • Vectored In te rru p t (VI) capability
• Wide operating tem perature: -40°C • Windowed Watchdog T im er (WWDT)
to +105°C Infineon • 3 2 -b it Cyclic Redundancy Check
• Power m anagem ent m axim izes www.infineon.com (CRC) w ith SCAN
uptim e fo r b a tte ry applications • JTAG boundary scan
• UART, SPI and I2C
Analog Devices
www.analog.com Microchip Technology
www.microchip.com

DATASHEET URLS:

A na lo g D evices M A X 32660: h ttp s ://w w w .a n a lo g .c o m /m e d ia /e n /te c h n ic a l-d o c u m e n ta tio n /d a ta -s h e e ts /m a x 3 2 6 6 0 .p d f

In fin e o n EZ-PD CCG7D: www.infineon.com/dgdl/Infineon-CYPD7291_EZ-PD_CCG7D_Automotive_USB_Type-C_and_Buck-boost_Controller-DataSheet-vl5_00-EN.pdf?fileId=8ac78c8c85ecb34701863803b0161a99

M ic ro c h ip T e ch n o lo g y P IC 18 F 2 7 /4 7 /57 Q 8 4: h ttp s ://w w l.m ic ro c h ip .c o m /d o w n lo a d s /e n /D e v ic e D o c /P IC 1 8 F 2 7 -4 7 -5 7 Q 8 4 -D a ta -S h e e t-D S 4 0 0 0 2 2 1 3 C .p d f


34 CIRCUIT CELLAR • AUGUST 2023 #397

Datasheet:
Application-Specific MCUs

nuvoTon

Highly-Integrated SiP SoC for High-Quality Audio MCU with DSP Power
for Low-Power Cellular Nuvoton's I91535ADI is an audio Based on the high-performance
T
E system-on-chip (SoC) integrated 100MHz 56800EF DSP core, NXP
E
H Applications with high-quality audio features and Semiconductors' MC56F80xxx digital
S
A The nRF9160 is a compact, a microcontroller in a single chip. signal controller (DSC) has an integrated
T
A
D highly integrated System-in-Package I91535ADI can run up to 49MHz with FPU and CORDIC/trigonometric math
(SiP) that makes the latest low- an embedded ARMCortex-MO 32-bit engine that provides high-performance,
power LTE technology and advanced microcontroller core and a 64K-byte flash cost-effective solutions for digital
processing and security accessible memory that has an additional 6KB boot power conversion and motor control
and easy to use fo r a wide range of loader flash and 20KB SRAM. The audio applications. This device combines the
single-device, low-power cellular features include a microphone input flexible functionality of an MCU with the
loT designs. Incorporating an Arm ADC and stereo DAC with a headphone processing power of a DSP, and includes
Cortex-M33 application processor output driver. The I91535ADI also comes high-speed, high-accuracy peripherals
solely fo r applications, a full LTE with a wide variety of peripherals, such like 8 channel eFlexPWM with 312 ps
modem, RF Front End (RFFE) and power as timers, a watchdog, peripheral direct resolution, dual high-speed 12-bit ADCs,
management system, the nRF9160 memory access (PDMA), serial interfaces, two operational amplifiers, a quadrature
is the most compact, complete and and more. decoder and three analog comparators.
energy-efficient cellular loT solution on
the market. • ARM Cortex-MO processor running • Enhanced single-precision floating
up to 49MHz point math unit (eFPU)
• ARM Cortex -M33 • 64KB Flash • Coordinate rotation digital compute
• 243 EEMBC CoreMark score running • 20KB SRAM (CORDIC) engine
from flash memory • 6KB Flash fo r user program loader • JTAG/EOnCE debug controller
• Data watchpoint and trace (DWT), (LDROM) • 64kB Flash
embedded trace macrocell (ETM), • ISP and ICP • 8kB SRAM
and instrum entation trace macrocell • 8x 16-bit PWM or 4x • Interm odule crossbar (support
(ITM) complementary paired PWM flexible connection among
• Serial wire debug (SWD) • 2x UART, 2x SPI, 2x I2C peripherals or GPIOs)
• Trace port • Event generator
• 1 MB flash Nuvoton • Enhanced DMA
• 256kB low leakage RAM www.nuvoton.com • Memory resource protection
• GPS receiver • LVI, POR and brownout reset
• RF transceiver for global coverage • CRC
• Internal and external watchdog
Nordic Semiconductor
www.nordicsemi.com NXP Semiconductors
www.nxp.com

DATASHEET URLS:

Nordic Sem iconductor nRF9160: https://infocenter.nordicsemi.eom/pdf/nRF9160_PS_v2.0.pdf

Nuvoton ISD91500: https://www.nuvoton.eom /export/resource-files/en-us-DS_ISD91500_DataSheet_EN_Rev2.4.pdf

NXP Semiconductors MC56F80XXX: https://www.nxp.com/docs/en/data-sheet/MC56F80XXX.pdf


circuitcellar.com 35

MCUs Optimized for Motor MCUs for Software-Defined Automotive MCU with Dual
Control Vehicles 32-Bit CPUs D
A
T
A
Renesas's RA4T1 group is optimized ST's Stellar 32-bit MCU fam ily meets Texas Instrum ents' Automotive S
H
fo r m otor control and inverter control the need for more powerful applications C2000 TMS320F2800157-Q1 E
E
functions, with small 32-pin QFN and and centralized electronic control units m icrocontroller has dual 32-bit C28x T
LQFP package options. RA4T1 delivers (ECUs) at the domain or zone level. CPUs in Lockstep, enabling the device to
up to 100MHz of CPU performance Stellar can run several critical real-time achieve ASIL B functional safety device
using an Arm Cortex-M33 core w ith a functions, support the aggregation and rating w ithout much SW overhead.
code flash memory ranging from 128KB dispatching of growing data streams, The real-tim e control subsystem is
to 256KB, 4KB of data flash memory, ensure efficient energy management, based on TI's 32-bit C28x DSP core,
and 40KB of SRAM. This collection of and secure OTA software updates to which provides 120 MHz of signal­
devices offers a wide set of peripherals, manage vehicle lifecycles and deploy new processing performance fo r floating-
including CAN-FD, I3C, and ADC. and improved services. Stellar delivers or fixed-point code running from either
enhanced motor control interfaces and on-chip flash or SRAM. The C28x CPU
• Arm Cortex-M33 Core an advanced generic tim er module is fu rth e r boosted by the Trigonometric
• Up to 256 KB code flash memory (GTM) to allow combining several power Math Unit (TMU) and VCRC (Cyclical
• 4 KB data flash memory (100,000 converters into a single control unit for Redundancy Check) extended
program/erase (P/E) cycles) the optimized management of vehicle instruction sets, speeding up common
• 40 KB SRAM dynamics. Specifications and datasheet algorithm s key to real-tim e control
• Connectivity: Serial Communications URL below are for the Stellar SR6 G7 line. systems.
Interface (SCI) x 2
• I3C bus interface (I3C) • AEC-Q100 automotive qualification • 32-bit lockstep dual-TMS320C28x
• Serial Peripheral Interface (SPI) x 2 on going core at 120 MHz
• CAN with Flexible Data-rate (CANFD) • 32-bit Arm v8-R compliant CPU cores • Dual security zones
• 12-bit A/D Converter (ADC12) • Two Cortex-M4 multipurpose • CAN-FD
accelerators • 256KB flash
Renesas • Four eDMA engines in lockstep • Watchdog tim er
www.renesas.com configuration Memories • Grade 0 and 1
• Up to 20.5MB on-chip NVM non­ • Hardware capability up to ASIL B
volatile memory and SIL 2 targeted
• 640KB data NVM (512KB + 128KB • Target market: automotive
dedicated to HSM) (examples: HVAC, on-board (OBC) &
• Up to 9280KB on-chip general- wireless charger)
purpose SRAM
Texas Instruments
STMicroelectronics www.ti.com
www.st.com

DATASHEET URLS:

Renesas RA4T1 Group: https://www.renesas.com/us/en/document/dst/ra4tl-group-datasheet

ST Microelectronics SR6G7x: https://www.st.com/resource/en/data_brief/sr6g7c4.pdf

Texas Instruments TMS320F280015x: https://www.ti.com/document-viewer/tms320f2800157-ql/datasheet


36 CIRCUIT CELLAR • AUGUST 2023 #397

The Magic Sm oke Factory

Intro to Control Systems


EM as EtaS @q® Etaft

gw
woseph Corleto

In this article, we embark on a journey through control engineering


experiments. This multi-part series aims to familiarize you with jargon
S and design techniques that are common practice in this engineering
N
M
U
subdiscipline.
L
O
C

ontrol systems are a wonderful and At the end of this series, I want to define some
complex subject. They're in our lives common terminology in the field so that, should
without many of us noticing or giving you be the lucky person tasked with solving a
them much thought. Obvious examples control systems problem, you can feel a little
include technologies like cruise control in our more informed and prepared. Along the way,
vehicles, or temperature control within our we'll use a real-life plant (as you'll find out
homes. But more subtle examples abound, such soon, this is not something that grows from the
as how toilet tanks magically "know" to refill Earth), and figure out how to control its behavior
the bowl after every flush, or how human bodies with industry-common solutions. Often, control
regularly regulate blood glucose levels with the systems use microcontrollers (MCUs) to both
help of the pancreas. When I graduated with measure and excite the actuating components
my BSEE degree over 10 years ago, I chose to that drive the system—I'll be using an ESP32-S3
specialize in this subdiscipline because it seemed as the platform.
like sorcery that I wanted to get my hands on.
After witnessing inverted pendulums dance on WHAT IS CONTROL SYSTEM
the edge of instability, levitating magnets defy ENGINEERING, ANYHOW?
gravity, and auto-positioning dart boards making Control system engineering is a discipline in
anyone look like a pro, I knew that I wanted to which you add components (called the actuator
sink my teeth into control systems. or controller) to a physical system so as to
But alas, the complex theory I learned in manipulate it to behave the way you want. Some
school did not align so well with what I've been physical systems may not need a whole lot of
exposed to in the industry. I'm not knocking my control engineering to get the desired behavior,
alma mater—what I learned there is indeed used while others need you to go to great lengths to
in the real world. But all my engineering positions achieve acceptable results. In general, there
to date haven't required the same level of theory. are two types of control systems: open-loop
What's the goal of this multi-part article? and closed-loop. What does that mean, you
Well, the way I see it, there are concepts and ask? Open-loop systems don't have feedback or
techniques in control systems that make electrical information on the current state or output of the
and computer engineers more marketable for system, while closed-loop systems do have a way
future jobs, and more effective at their current to grab information (often through sensors) to
roles. I'd like to offer a crash course in practical better control the output. The physical system to
control systems, without leaning on heavy math. be controlled is referred to as the "plant." By that
circuitcellar.com 37

I don't mean something like Audrey II from systems include washing machines, dryers,
Little Shop of Horrors, but a factory or place light bulbs, and addressable RGB LEDs.
where something is made—for example, a
power plant. MAJOR PARTS OF A CONTROL
An example of an open-loop system is a SYSTEM
toaster oven. Bread goes in, gets heated for Closed-loop systems come up often, as
a certain amount of time, and the result is a they're used for precise control in many
toasted piece of bread. What if we took that engineered systems. But we'll also look at
same piece of toast and placed it into the open-loop responses initially to help us better
oven again? Well, it would do the same thing understand these systems. There are a ton
again, and we will probably wind up with a of things to consider when figuring out how
burnt piece of bread. The goal of the system a plant should behave and how to control it.
is to toast bread, with the assumption that But before we get to those details, we need
each piece you place in it is at a consistent to understand the major parts of a control
and known initial state. It never measures the system. Whether open- or closed-loop, the
current toastiness of the bread. To do that, it terminology is the same.
would need to be closed-loop. In other words, The input in a control system is referred
it would need to have sensors to measure the to as the "reference" or "setpoint." It's where
bread's initial toastiness. In a closed-loop you'd like the system to operate functionally.
toaster oven, if a piece of bread was already For example, the setpoint for a temperature
toasted beyond a given toastiness setting control system is typically an operating
chosen by the user, the toaster would turn off temperature. The output of a control system
immediately. This same behavior is seen at is known as the "controlled variable" or
gas stations when a gas pump clicks off when "process variable." It's the current state of
C
it detects that your car tank is full so that you the plant, where it's operating at a moment O
L
don't overfill your tank. in time. In the same example, it would be the U
M
Another practical example of a closed- current temperature of the medium or device N
S
loop system is an air conditioner. When you whose temperature is being controlled.
set it to a certain temperature, it continues Great! We now have enough to draw
to blow cool air until the room reaches that a block diagram of a typical closed-loop
temperature. Once it does, the AC turns off, control system (Figure 1). Notice the "input
and re-engages when the room becomes transducer" block right after our setpoint.
too warm again. If the AC were open-loop, it This is a physical system to help convert our
would cool the room constantly, at whatever setpoint command into something the control
level it was set at. That could mean it does an system will understand. For example, it could
okay job, or that it over- or under-performs. be a dial to change a voltage going to an MCU
Open-loop control and closed-loop control or some other sub-component. The other block
both have their time and place. Usually, is the sensor, which measures the current state
consistent, predictable initial conditions of the controlled variable. This measurement
warrant the use of open-loop systems, is then sent back to a summing junction to
especially if you want to save cost on extra generate an error or actuating signal for the
components (like a toastiness sensor). They controller to interpret. What type of output
also lend themselves well to cases where the the controller produces is completely up to the
result doesn't need to be too precise. If your designer to create. It's where the brains are
bread's initial state changes, you can offset it hidden in the control system.
by changing the heating time/level settings— The system in Figure 1 is classified as
or just deal with a less toasty (or over-toasted) a single-input single-output (SISO) control
piece of bread. Other example of open-loop system. Most people will come across SISOs.

FIGURE i
A general block diagram of a closed-
loop control system. (Source:
Control Systems Engineering, 6th
Edition, page 8)
CIRCUIT CELLAR • AUGUST 2023 #397

FIGURE 2
system [1]), I think it would be too much
A silicone heater that is listed on
of a distraction, and too costly to build for
Amazon. There is a nichrome wire
newcomers. Instead, the plant in our example
inside that can be powered to
will be a heated silicone mat used for 3D
warm the surface. There is also an
embedded thermistor inside. printer platforms. Specifically, the "Signswise
200mmx200mm 12V 220W silicone rubber
heating heater for 3D printer heated beds"
(Figure 2). Rolls right off the tongue! No, it's
not as sexy as a levitation control system.
But temperature control systems pop up
often, so it's worth learning from one. Hey,
I even used a toaster and heater example
earlier in this article— maybe that was a bit of
foreshadowing.
Let's have a look at Figure 3. The silicone
surrounds an internal heater, likely Nichrome
wire, along with a thermistor, all shown in the
figure. The silicone heater will be our plant,
and the thermistor our sensor. The controller
will be a good ol' ESP32-S3, coupled with a
CMX60D20 solid-state relay. Electrical specs
that are important to note are the input
voltage and load current. The minimum input
voltage required is 3VDC. Since our I/O for
the ESP32-S3 is 3.3VDC, we should be good
to go. Our heater is specified to be rated at
12V, 220W. This means that it can handle
There are more complex structures, such 18A—yikes! The SSR I chose can handle 20A,
as multiple-input multiple-output (MIMO) but this is reaching its limit and will likely
control systems. The design process for these need something to cool it under operation,
is vastly more complicated, requiring the aid like a fan. Not only that, but I also don't have
of sophisticated simulation tools and accurate a power supply that can source that much
plant models. Specifically, MIMO systems current, and pushing the silicone heater to
are typically designed with "state-space its limit is not something I'm a...fan of doing.
representation." State-space representation, Instead, I have access to a power supply that
in a nutshell, is a mathematical model of sources almost 7A when I have the outputs
the entire control system that details how internally wired up in parallel. It might be a
a system evolves over time. It is said to be little slow to heat up, but for demonstration's
represented in the time domain, and the stake, it'll do.
mathematics involve first-order differential
equations written in matrix form. But don't RISE TIME, OVERSHOOT, AND
worry about that! This article series will only STEADY STATE ERROR
deal with SISO systems, as these are sufficient I had no choice but to provide a lower-
to give us a firm grasp of some core control than-necessary current through the heater
engineering concepts. due to equipment limitations in my lab.
But this isn't unusual in our world, and
OUR CONTROL SYSTEM sometimes underpowering the plant is a
DEMONSTRATION PLANT good thing— by not pushing our heater to
As much as I'd like to use an eye­ its limit, we can preserve its integrity and
catching plant (like, say, a magnetic levitation operational lifetime. However, by doing this,

Temperature Heater
Setpoint Temperature
FIGURE 3
Our example control system that
we'll be messing around with. Notice
that all the elements of a closed-loop
system are present.
circuitcellar.com

we're limiting our plant's operating speed.


That is, we're slowing down its "rise time."
Rise time is defined as the time it takes to
get from an initial operating state to another.
For the initial state, rise time is typically
counted as the time it takes to get from 10%
of the setpoint to 90% of the setpoint. These
sorts of requirements—where the system
needs to last long in the field, not use as
much power, and not stress components—
are common in control system projects. But
it's important to understand that adhering
to these requirements will most certainly
increase the rise time. Figure 4 illustrates
a rise time measurement scheme. As a side
note: the lower current through our heater
will not only affect the plant's rise time, but
also how hot the heater can potentially get
as well.
There is another requirement that needs
FIGURE 4
to be defined: how much overshoot is allowed.
Definition of rise time measurement (Source: University of Illinois Urbana-Champaign [2])
"Overshoot" is the maximum amount that
the system exceeds its setpoint, divided by
the setpoint, which makes it a percentage.
This requirement greatly depends on your
system. For our silicone heater, I am okay industry, so just because I haven't used most
with some overshoot— let's say 5%. For other of what I learned in school does not mean
systems, overshoot could be detrimental or these are never used industry.
flat-out annoying. Ever been on an elevator
where it goes slightly past the floor it is ON/OFF CONTROL
supposed to stop on, only then to slowly As I said, the first control law I see
even itself with the floor? I have, and it is regularly in the industry is the on/off
incredibly irritating! control, or bang-bang control. It's simple
Finally, we have the "steady-state error." to understand. The actuation to the plant is
It is defined as the difference between the only one of two states: on or off. That is to
reference and the setpoint. An example say that if we have not reached our setpoint
would be if we commanded our temperature yet, fully actuate the plant. Once we are at
controller to operate the silicone heater at or past the setpoint, stop all actuation to the
100°C, but instead it is at 99°C, resulting in plant. To spare our components from intense
a steady state error of 1°C. Again, this totally wear and tear—for example, a relay—we can
depends on the requirements in question. For introduce a bit of hysteresis. This means
me, I would like to have a steady state error
of less than 0.5°C.

CONTROL LAWS
A control law is an algorithm contained
within the controller. It holds the method of
what to do at a certain point in time over the
operation of the system. This translates to how
much actuation should be directed toward the
plant given the error signal dynamics. There
are a ton of control laws out there. To name
just a few controllers: on/off (also known as
bang-bang), proportional-integral-derivative
(PID), feedforward, pole placement, linear-
quadratic, and fuzzy logic.
As a side note, I have used almost all of
these in an academic setting when I was a
student in controls classes, but I have only
seen two in my engineering career: on/off FIGURE 5
and PID control. Please note that I have never On/off controller response behavior. Notice that oscillations are present, causing something
been a full-fledged controls engineer in the marginally stable. (Source: eeeguide.com)
CIRCUIT CELLAR • AUGUST 2023 #397

plant does not need hysteresis because it can


respond fast to actuation—essentially getting
rid of the oscillation—there is usually some
downside. For electro-mechanical relays,
their contacts wear out quickly. Electrically
controllable valves may overheat and get
damaged. In high-power systems with solid-
state components, there are too many high
voltage and current transients degrading the
system's lifetime. As a result, on/off control is
reserved for only the simplest control systems
that have loose requirements. Figure 5 shows
the stability response of a typical on/off
controlled system.
FIGURE 6
Block diagram of a PID controller. (Source: researchgate.net) PID CONTROL
The second control law I see frequently
in the industry is PID control. It's not at all
like the on/off controller. Instead of having
that depending on the state of the system, two states for actuation, we actuate (mostly)
we can introduce a bit of actuation lag once anywhere from fully off to fully on. For
the setpoint is met. For example, if we need example, instead of applying OV or 12V to a
a heater to be at a nominal temperature of heater, we can apply 2V or 6.5V, or whatever
100°C, instead of turning off the power to it our PID controller deems necessary as the
right when it reaches this setpoint, we can actuation to the plant. And in general, this
have our controller cut the power at some is how most control laws that offer precise
amount above this—maybe 102°C. Once this control need to be. To better understand the
occurs and power is turned off, we can do the PID control scheme, check out Figure 6.
same thing in the other direction: At 98°C, When you look at this the first time
we can turn the power back on. Essentially, around, it can be intimidating—thanks in no
it's like having two setpoints based on the small part to the calculus notation. For now,
situation at hand. just think of PID control as three separate
This simplicity comes at a cost, however. operational control laws: present, past, and
Even though we can generally control a future. The proportional block applies control
plant within a certain range, we can almost over what is occurring now in the system. The
never get to precisely operate it where we integral block applies control based on what
want it to be. The output behavior tends to happened in the past. The derivative block
be oscillatory as a result. Meanwhile, if our applies control based on how things might
look in the future.
And th is is where I am going to ask for
ABOUT THE AUTHOR some patience on your side for a future
Joseph Corleto holds a Master's Degree in Electri­ article, as I want to give this type of control
cal Engineering. Aside from working as a full-time the proper treatment. If I start intermingling
Electrical Engineer, he has a small business (Bit PID control without looking at some open­
Bang Gaming LLC), which creates video game elec­ loop response and basic on/off controls, it
tronics hardware, and is actively pursuing the cre­ would get confusing. So, without further ado,
ation of a project-based video course using the let's introduce our plant.
ESP32. He describes himself as an Electrical Engi­
neering handyman since he has skills in firmware,
CONCLUSION
I know: the fun is over already? Yes, it's
R&D, PCB design, PCB assembly, and automated
closing time, go home (or turn the page and
testing. You may reach him anytime via his email:
read Mike Lynes's technical poetry). But I
Corleto.joseph@gmail.com.
hope that this article has piqued your interest
in control systems. In the next piece, we're
going to take a look at some open-loop
responses of our plant to get a feel for how it
Additional materials from the author are available at:
behaves. And then we'll try to apply the on/off
www.circuitcellar.com/article-materials
control law and see how we can get it to
References [1] and [2] as marked in the article can be found there. behave as we wish. Will it be good enough?
Will PID control have to come in and save the
Resources day? I guess we'll have to wait and see. Thank
Espressif Systems | www.espressif.com you for reading!
circuitcellar.com 41

rt to Finish

Hbt in
Basics

area
go ven

C
O
L
ave you ever built a circuit that An ideal digital integrated circuit, like an U
M
dissipates power, such as a ideal wire, would dissipate no power at all. N
voltage regulator or audio power Every component inside the part would either
amplifier, and wondered how to be using zero current or have zero voltage
keep it cool? Ever wonder how Intel chooses across it, so VI would always be zero. But
the heatsink and fan for the CPU in a desktop unfortunately, you can only find zero-power
PC or server? Why do people go to the expense integrated circuits in the physics department of
of water cooling a PC or other system? your local university, on the same shelf as the
Keeping electronics from overheating is an massless ropes and the frictionless surfaces.
important part of circuit design. It's both a Since real integrated circuits dissipate
scientific process and a little bit of magical power, they generate real heat. In some cases
mystery. (I say "magical" because sometimes that heat must be transferred elsewhere to
you don't know everything you need to know avoid overheating the device. And that's where
to make it pure science.) thermal management has to happen. I'll focus
The goal of thermal management in most only on semiconductors in this article, but the
electronics is to keep the semiconductors same principles apply to things like power
from overheating. Other parts can overheat resistors.
as well—see my Circuit Cellar article about
resistors ("Getting Started with Resistors: THERMAL PARAMETERS
Workhorses Devices," Circuit Cellar 382, May For an integrated circuit, it's important
2022) for more detail about that [1]. to keep the junction, the semiconductor
element, from overheating. The word
POWER "junction" might imply that there's only one
Any electronic component—whether junction in the device; this is a carryover
integrated circuit, transistor, resistor, motor, from the days of transistors. "Junction"
or any other part—dissipates power when means the semiconductor inside the IC
current flows through it. The power dissipated package, regardless of how many transistors
in the device gets turned into heat. Even a it contains.
wire dissipates power, although if the wire is The important thermal number is the
sufficiently large, it doesn't dissipate much. A junction-to-ambient thermal resistance, R0 .
wire may carry 100A to an industrial welder R0 can be just the R0 of the part, or the R0 of
without dissipating much power in the wire the part plus additional components such as a
if the resistance is low enough. Power is heatsink. This is a measure of how efficiently
calculated as VI—voltage times current. So, the package transfers the dissipated power to
the power dissipated by a wire or a resistor is the ambient temperature. Thermal resistance
the voltage across the wire times the current is expressed in °C per watt. A TO-220 package
through the wire. might have an R0 of 50°C/W, which means
CIRCUIT CELLAR • AUGUST 2023 #397

FIGURE 1 For a power IC there will normally be at


TO-220 heatsink
least two thermal resistances specified: the
R0 of the junction-to-ambient (usually R0 ja),
and the R0 of the junction-to-package (R0 j P)
which applies if you have something attached
to the power tab. Connecting a heatsink to the
power tab provides a better transfer to the
ambient temperature.
Thermal resistance of a device is supplied
by the manufacturer. The calculation for
thermal resistance requires that you know
the surface area of the material, the thermal
conductivity, and the thickness of the portion
of the material between the junction and
ambient air. It's impractical for someone
that if the part is dissipating 1W, the junction designing with a part to know all of that,
temperature will be 50°C above ambient. especially about an IC, so the manufacturers
Ambient temperature is important provide it in the datasheets.
in thermal management because the Since there's no way to get heat out of the
temperature of the IC case can never be device other than through the device package
lower than the ambient temperature. Say an (which includes the power tab, if there is
IC has a maximum junction temperature of one), the entire goal of thermal management
125°C and has 100°C/W R0 . If the device is is to efficiently transfer heat into the ambient
dissipating 0.5W, then the junction will be surroundings. "Ambient surroundings" isn't
50°C hotter than the ambient (0.5W x 100°C/W necessarily the temperature of the room.
= 50°C). So, if it is dissipating 0.5W, then to It might be the temperature inside the
avoid overheating the device, the maximum enclosure, or the temperature of the chassis
ambient temperature is 125°C - 50°C, or if the chassis is used as a heatsink. A passive
75°C. (I'll be rounding temperatures to the heatsink can't cool a device below ambient;
nearest degree.) the best you can do is get it closer to ambient.
Figure 1 is a photo of a heatsink for a TO-
rioctnco# F quivdent 220 package. This would typically mount on
a PCB. The fins are intended to maximize the
Scn^ conducts PCB (at ambient
Junction temperature) surface area for efficient transfer of heat.
R0 is treated mathematically as ordinary
electrical resistance. Figure 2 illustrates this:
an IC such as a voltage regulator is connected
to a metal plate that functions as a heatsink,
which is attached to the PCB. Say the IC
package has an R0 of 10°C/W and the metal
plate has an R0 of 20°C/W. So, the total R0
between the IC junction and the PCB is 10 +
20 = 30°C/W. The PCB itself will have some
thermal resistance to the ambient air, or to the
chassis that it mounts to. Thermal resistance
is essential in determining whether you need
a heatsink in your circuit, and what kind.

DO YOU NEED A HEATSINK?


You might not be sure if you need a
heatsink on a given part. You can determine
this by the following equation:

Tj = Ta + (P x R s )
where Tj is the junction temperature, Ta is
the maximum expected ambient operating
temperature, P is power in watts, and R0
is the thermal-to-ambient temperature in
°C/W. If Tj exceeds the maximum junction
FIGURE 2
temperature, then you need a heatsink. And,
IC mounted to PCBA with metal
plate
of course, you need to know the maximum
circuitcellar.com

ambient temperature and the maximum temperature. The small brass fin isn't much
power that will be dissipated. of a heatsink, but it provides a lower R0 than
the copper tape. Cooling with just the brass fin
EXAMPLE CIRCUIT depends on convection. Adding the fan reduces
Figure 3 shows the schematic of a simple the R0 further because even the brass fin can
circuit that I built to illustrate some of these transfer heat better into moving air.
concepts. Figure 4 is a photo of the circuit,
an LF33 3.3V regulator in a DPAK surface­ SELECTING A HEATSINK
mount package. The DPAK (which is the same Now I want to extend the example and
as the TO-252 package) has two leads—input select a real heatsink for a real device. The
and output—and a tab for ground. The tab is LF33, like a lot of linear 3-terminal regulators,
normally soldered to a copper land on a PCB. will shut down if it gets too hot. But, although
In this case, I soldered it to a piece of 0.25" x that protects the device, having our piece
2" adhesive-backed copper tape and attached of equipment randomly shut down for no
a small ring-terminal thermistor to the copper apparent reason will not make it very useful
tape so I could measure the temperature of the and will annoy the user. So, we want to keep
LF33. The thermistor is probably not exactly at the device cool enough to prevent that.
the temperature of the IC case, but it's close The LF33 comes in both DPAK and TO-220
enough to demonstrate the principles involved. packages. The TO-220 has a power tab with
The circuit is powered by a 5V input and a mounting hole for a heatsink. The TO-220
the load resistor R1 draws 330mA, dissipating package has the same maximum junction
1W (PR). The LF33 also draws 330mA, and temperature of 125°C, but the junction-to
has 1.7V across it (the 5V input minus the ambient R0 is 50°C/W, half that of the DPAK
3.3V output), so it dissipates 560mW (1.7V x package, and the junction-to-case R0 is 5°C/W.
330mA). The thermistor is used to calculate the Let's say we're going to supply the LF33 with
temperature using the resistance (measured an 8V input and it must supply 300mA to the
with a DVM) and a handheld calculator (see circuit it's driving. The dissipation of the LF33
my aforementioned resistors article for a will be (5 - 3.3) x 300mA, or 1.41W. Without
description of thermistors [1]). a heatsink, the junction temperature will be
According to the LF33 datasheet [2], the 1.41 x 50, or 70°C above ambient.
DPAK case has a junction-to-ambient R0 of With these parameters, the maximum
100°C/W. The LF33 junction-to-case resistance ambient temperature is 125 - 70, or 55°C.
is 8°C/W from the power tab. The copper tape And really, it's lower, because you don't want
and the solder and even the ring terminal to run the part right at the thermal limit.
on the thermistor provide some amount of Let's suppose the design specification says
thermal heatsinking. For the calculations it has to operate in an enclosure where the
here I'll use the junction-to-case resistance temperature can reach 60°C. How do you find
since the thermistor will be very close to the an adequate heatsink for that?
temperature of the mounting tab. The ambient The heatsink must have an R0 to ambient
temperature when I did this was 23°C. that will prevent the LF33 from exceeding the
Without the copper tape heatsink the junction maximum junction temperature at an ambient
would be at 23°C + (560mW x 100°C/W), or temperature up to 60°C. Since we'll be using
79°C. I applied power to the circuit and the the TO-220 power tab for mounting, we'll
temperature stabilized at 53°C, or 30°C above use the junction-to-case R0 . The LF33 will be
ambient. So, the junction temperature was the mounted with a thermal pad or with silicon
case temperature + (power x R0 ), or 53°C + grease to improve the thermal connection.
(560 mW x 8°C/W) = 57°C. The total R0 to ambient is the package R0
For the second experiment, I soldered a + the thermal pad/grease R0 + the heatsink
0.032" thick x V2" x 2" long piece of brass to R0 . For this calculation, I'll say the R0 of the
the heatsink. This was soldered to the top of thermal pad is 1°C/W.
the LF33 ground tab, so it had good thermal
contact with the LF33. In this configuration,
the temperature was 48°C. Doing the same
math, the junction temperature was 52°C, or
5°C cooler.
I then added a 2" fan to blow air over the
fin; the temperature came down to 28°C—
just 5°C above ambient—making the junction
temperature 32°C. So even in this simple
experiment, you can see that improving
the ability to transfer heat into the ambient FIGURE 3
surroundings is key to controlling device Schematic for the test circuit
CIRCUIT CELLAR • AUGUST 2023 #397

So, we need a heatsink large enough that 500 linear feet/minute (LFM) airflow, the R0
the temperature of the LF33 junction remains of the part drops to 10°C/W, a 3:1 reduction.
below 125°C with an ambient of 60°C while
dissipating 1.41W. The heatsink (with the THERMAL GRADIENTS
thermal pad) makes the thermal "connection" When choosing an off-the-shelf heatsink,
between the case and the ambient air. you'll want something with a thermal
The total R0 of the package, thermal pad, resistance that's a little lower than the
and the heatsink together is: calculations indicate. This is because the
manufacturer characterizes the heatsink
R @ jc "I” R ® tp R @ hs based on some configuration, such as a plate
that covers the surface of the heatsink and
distributes the heat evenly. In reality, a TO-
R0 jC is the device's junction-to-case thermal 220 power tab in this example doesn't cover
resistance (5°C/W), R0 tp is the thermal pad the entire surface of the heatsink, so there
resistance (1°C/W), and R0 h s is the heatsink is going to be some difference between the
thermal resistance. The temperature rise theoretical thermal resistance and the actual
(125°C - 60°C) when using a heatsink is then: thermal resistance of the heatsink attached to
the actual part.
Power x (R 0jc + R Olp + R s h s ) The material of the heatsink also has some
thermal resistance. There's a temperature
gradient on the heatsink as you move away
Power is 1.41W in this example, as from the heat source. To put it simply, there's
discussed. Doing some algebra to find the a thermal resistance between two points on
total thermal resistance, we get: the heatsink itself.
To demonstrate this, I wired a 7805 linear
r + RK +R (125-60) 46°C regulator with a 5Q (0.5A) load and attached
,'‘0JC- Ol|i K 0hs 1 4 1 w w
it to a 3" x 0.9" scrap piece of 0.064" thick
aluminum. Figure 5 shows the circuit and
R0 jc = 5°C/W and R0 tp is 1°C/W, so: the mechanical construction. The 12V supply
was unregulated, so the 7805 was dissipating
_ (125-60) _ 40°C about 4.5W. I used a thermocouple to
^0hs L . J ^0jc R 0tp
measure the temperature along the length of
the aluminum piece, and it varied from 95°F
So, the heatsink thermal resistance must right at the 7805 power tab to 91°F at the
be 40°C/W or less. Looking through the Digikey opposite end (the meter had 1°F resolution).
online catalog for TO-220 heatsinks, we find Not a lot of difference, but then this example
that the Aavid 577002B00000G, with an R0 of isn't dissipating a lot of power. But allow some
32°C/W, works, and with a little margin. With margin in your design.

WORKING IT BACKWARD
I'm going to create a ridiculous scenario
to illustrate how this works in reverse. Say
you have my original DPAK LF33 experimental
circuit with the brass fin and copper tape.
But now you want to take the board to
production, and you need to have the same
thermal characteristics but with an off-the-
shelf heatsink.
From the previous experiments, the
temperature of the device is 48°C, or 25°C
over ambient. R0 of the combined brass fin
and copper tape can be calculated this way:

' 25°C 45°C


Heatsink R 0 —
v 560mW, W

So, you'll need to find a heatsink that has


an R0 less than 45°C/W.
Suppose there's a new requirement:
the current product uses a fan to keep the
FIGURE 4 regulator cool but the fan is a high-failure
The test circuit item (as fans often are). You need a heatsink
circuitcellar.com 45

that will cool the device without using the fan. In my provides a more efficient mechanism to transfer the heat,
experiment, the fan brought the case temperature down to making the cooled part closer to ambient. The only way to get
28°C. I don't even know how much air the fan was providing, the part colder than ambient is to use chilled liquid.
but it doesn't m atter—we know how much the fan lowers the You can also get Peltier coolers that cool on one side and,
temperature. I'm ignoring the junction-to-case temperature of course, heat on the other. You still have to get rid of the
of the device here. We know the case temperature from the heat; the laws of thermodynamics make sure there is no such
previous measurements and just have to keep that the same thing as a therm al-free lunch. By attaching a heatsink and/
as the original circuit. or fan to dissipate the heat, Peltier coolers can lower the
With the fan, the total Re is (28 - 23)/560mW or 9°C/W temperature of the IC package, even lower than ambient. But
(fan + copper tape + brass fin). So, you need a heatsink with Peltier coolers are inefficient—they need significant power
an R0 less than 9°C/W. That's going to be a large heatsink, input to produce significant cooling, and they need a very
and it may be difficult to transfer the heat into the heatsink efficient heatsink on the hot side. From a system perspective,
efficiently from the DPAK power tab. If you were doing this you will produce more additional heat in the power supply
in a real application, you would want to switch to the TO220 than you will pull out of the device you are cooling. But there
package, which will transfer heat better into the heatsink. may be situations where you want the device to be cold and
The real calculation is a bit more complicated than that since don't care how much power it takes to do that.
removing the fan may raise the ambient temperature inside
the enclosure, so more thermal analysis of the entire system is MEASUREMENT
needed. That's an important point: when you use any kind of Thermal modeling software can predict how hot things will
heatsink to draw heat away from a device, something else gets get, especially when designing a custom heatsink. But sometimes
hotter, whether it's ambient air, the case, or something else. there is no substitute for measurement. You do the best design
you can and then measure the hot devices with thermocouples
CASE HEATSINKS: or an IR gun to make sure they don't get too hot.
Sometimes the case of the product is used as a heatsink.
C
This was common some years ago with audio am plifiers and CONCLUSION O
L
large computer power supplies. Some parts, such as the ST A lot of circuit designs don't need to be concerned with U
M
TDA7292 audio power amplifier, are intended for a large cooling. But when you do need some kind of thermal management, N
S
heatsink such as the chassis of the equipment. You will usually it's important to be able to calculate what will work. Hopefully,
need to do some thermal analysis of the case to ensure that this article has pointed you in the right direction.
the part won't overheat. Many years ago, I developed m ilitary
electronics that had to be in a fully enclosed, waterproof
housing. In that case, the aluminum enclosure was the only
heatsink available.

PCB COPPER HEATSINKS:


Copper on a PCB can act as a heatsink. Depending on
whose numbers you use, a square inch of lo z copper has
an R0 of about 50 to 100°C/W. 0.063" FR4 PCB material has
an R0 of about 10°C/W, so the board itself will provide some
cooling. A larger copper area provides a better heatsink,
but because the copper layer is so thin, it doesn't transfer
heat as effectively as an equivalent piece of, say, 0.064" thick
aluminum (see the section on thermal gradients). But for
surface mount parts, PCB copper is often adequate. Some
ICs specify that a certain amount of copper area should be
connected to specific pins or to an SMT pad under the device.
FIGURE 5
A ceramic PCB (instead of FR4) has a lower thermal resistance.
Thermal gradient on a 7805 regulator and aluminum strip heatsink
You can also get heatsinks that solder to a PCB to increase the
effectiveness of a copper-pad heatsink.
ABOUT THE AUTHOR
ACTIVE COOLING Stuart Ball recently retired from a 40+ year career as an
As already mentioned, you can direct air over a heatsink electrical engineer and engineering manager. His most
to improve heat transfer, lowering the effective thermal recent position was as a Principal Engineer at Seagate
resistance. Fans tend to be relatively high-failure parts, so if Technologies.
your design depends on a fan, then you should be monitoring
it and take some action if the fan stops or if temperatures get
too high. And, again, a fan can take the temperature closer
to ambient, but not below it. No amount of air movement will Additional materials from the author are available at:
make the part cooler than the air itself. www.circuitcellar.com/article-materials
Another type of active cooling is a liquid-cooled heatsink, References [1] to [2] as marked in the article can be found
where liquid is pumped through the heatsink, then cooled in there.
a heat exchanger, and reused. The liquid-cooled heatsink just STMicroelectronics | www.st.com
46 CIRCUIT CELLAR • AUGUST 2023 #397

E m b e d d e d in Thin S lices

Debugging Embedded
Real-Time Systems
Strategies for Finding Bugs
This month, I wrap up this article
series with a list of proven strategies
that I've used in finding bugs in
embedded real-time systems.

Bob Japenga

S
N
M
U
L
O FIGURE 1
C
Left Ventricular Assist Device (LVAD)

number of years ago, a product we regarding what could be causing the bug.

A developed for one of our customers


had a bug that prevented us from
shipping. (Oh, would that this was

because I was an expert, but because I was


a good wall to bounce ideas off of—and spent
Thinkabout what else might be going on if this
bug is happening based on this hypothesis.
In other words, ask yourself: "If this is the
problem, what else also must be happening?"
true for all companies!) I was called in—not
Next, prioritize these hypotheses from most
likely to least likely. This prioritization doesn't
several days with our top designer futilely need to be perfect. Then attempt to prove the
trying to find that bugger. After several days, hypotheses wrong by building test cases one
I realized that we both had different strategies at a time around each in order of priority.
that we were applying to find the bug. It was A trivial example might be the hypothesis
the first time that I realized how many different that there is a concurrency issue causing
strategies there were for finding bugs. And I some data corruption. With most good real­
learned from him. I honestly don't remember time operating systems, you can change
whose strategy finally proved successful, but the scheduling algorithms with a compiler
in all probability, it was his. But it showed me switch to a non-preemptive scheduler. We
that we need to apply multiple strategies in implemented this strategy once and found
finding those bugs that bug us. This month, something we weren't looking for. We were
we'll look at some of my favorite strategies. using real-time extensions in Linux (before
they were built in) to achieve deterministic
STRATEGY #1: "COULD IT BE?" operation on an output controlling a balloon
One strategy that I found useful in finding pump triggered by an electrode measuring
bugs revolves around building a series of heartbeats (Figure 1) [1]. Much to our
hypotheses as to what could cause the problem. surprise, we discovered that non-pre-emptive
First, gather as much data as you reasonably scheduling of our tasks did not appear to
can about the bug. Asking questions like: change the repeatability of our balloon pump.
What is going on when it happens? How does But repeatability after two days in the lab with
it manifest itself? How often does it happen? one system is not the same as 10 years with
And so on. Then brainstorm with some others 10,000 units in operation. Needless to say, we
to create as many hypotheses as you can stuck with the real-time extensions.
circuitcellar.com

STRATEGY #2: HANSEL AND GRETEL


Most of us are familiar with the story
of Hansel and Gretel (Figure 2). Having
overheard a plot by their stepmother to
abandon them deep in the forest, they drop
pebbles along the path and easily find their
way home following their abandonment. This
strategy uses some kind of marker that can
lead us to the source of the bug. The marker
can be printf's, LEDs, log files, GPIO outputs,
or any appropriate pebble that can indicate
the steps leading up to the bug. Of course, on
the step-mother's second attempt, the bread
crumbs are eaten before Hansel and Gretel
try to come back. Make sure your markers
don't get "eaten."
This strategy's incredibly important, given
the nature of many hard-to-find bugs. A study
published in Communications of the ACM
found that a large percentage of hard-to-find
bugs happen when large temporal or spatial
chasms exist between the root cause and the
manifestation of the bug [2]. A pebble trail
can help bridge that chasm.
For example, imagine state-driven
software that "randomly" fails in some way.
Recording all the states with a timestamp
could reveal that the failure occurs after FIGURE 2
the software was in a particular state after For example, imagine that you're Hansel and Gretel
having been in another particular state. And experiencing some buffer overwrite condition.
the failure could be temporally distant from But who's causing it? Start paring down your
the software being in either state. system in a binary fashion. First, cut out half
of the possibilities. And then half again based
STRATEGY #3: EAT YOUR EGO on your results. If you have 10 tasks, cut out
We have already mentioned bringing in five, and then three, and so on—not one at
extra help. But I'm embarrassed at how a time. Or use the technique to pare down a
often, when I've done so, my helper has function—not in little chunks, but by half and
found the bug immediately. This works then half again.
counterproductively with those of us who Time is money in our game, and the
have not learned humility. The more often divide-and-conquer strategy can help you
it happens, the more reluctant I am to call find bugs more quickly.
in help the next time. "I'm not going to be
embarrassed again." Or, "I have to be able STRATEGY #5: PRESS THE PAUSE
to find this on my own." So, eat your ego BUTTON
and get help—soon! See Figure 3 for a visual I am amazed at how our brains work. They
reminder. often solve problems in our sleep. Sometimes
the best debug strategy is to pause and give it
STRATEGY #4: DIVIDE (BY TWO)
AND CONQUER
I distinctly remember the first time I used
a binary search on some large structures. (I
think it was in FORTRAN IV, to date myself).
I was pleasantly surprised at how much
faster it worked than a simple linear search.
The "divide and conquer" strategy starts by
simply taking out code to isolate the bug.
With interrupts turned off, does the bug still
happen? When we don't run the built-in test
thread, does the problem go away? I've found
that using the binary search technique with
this strategy helps immensely to narrow FIGURE 3
down the source of the bug quickly. Eat your ego!
48 CIRCUIT CELLAR • AUGUST 2023 #397

FIGURE 4 In Zen terminology, this is called harnessing

PAUSE
Pause
the beginner's mind. The Zen monk Shunryu
Suzuki once said: "In the beginner's mind
there are many possibilities; in the expert's
mind there are few." We all have probably
been there. We are in a marathon session with
a deadline and a boss breathing down our

II
neck. Our intense focus can cause us to miss
the obvious. We miss that we have confused
our assumptions with facts. We accept things
that are just plain wrong. We have rejected
some possibilities for no good reason. This is
where adopting a beginner's mind can help.
a rest. Take a walk. Go home. Take a nap. Like
strategy #3, our egos will resist this strategy. STRATEGY #8: LOOK AT THE CODE,
"I'm almost there." "If I can find this, I will NOT THE COMMENTS OR LABELS
be able to go home in peace." Don't give in to The names and comments in the program
these siren calls. Give your brain a rest. Press code can throw us off since they indicate
the pause button (Figure 4). what the computer is supposed to be doing,
not necessarily what we actually told it to
STRATEGY #6: WRITE DOWN do. A classic bug that I often introduced was
WHAT YOU'VE TRIED reversing the Boolean logic on the return of
Often, I have tried so many things to find a function or the labeling of a variable. For
some stupid bug, that I start repeating things example:
S I had tried before. I know it takes more time,
N
M but write down the methods you've tried, the if (OutputlsOn(som eOutput))
U
L steps that you've taken, the paths that you've
O
C already traveled. And start doing this right // Operate on the On c o n d itio n
from the beginning—before you know how
long it's going to take to find the bug. el se

STRATEGY #7: BE AS DUMB AS // Operate on the O ff c o n d itio n


THE COMPUTER
A former co-worker, Mike Scudder, wrote
me this as I was writing this article: "Another while the function itself is returning false if
technique I often use, once I have identified the output is on. Or when we define a variable
a relatively manageable series of statements where the name is opposite to its value like:
that should contain the bug, is to process
them mentally (or perhaps on paper) while bool TanklsEmpty;
striving to be as dumb as a computer. Often
the bug stems from treating the computer as which we define as true when the tank is not
if it had common sense, when it is actually empty.
and always instead doing exactly what you
told it to do." STRATEGY #9: DUMP AND DIFF
Digitally comparing core dumps or
extensive log files is often a helpful strategy
ABOUT THE AUTHOR
for finding differences in data structures
Bob Japenga has been designing embedded that are voluminous. Use automated tools
systems since 1973. From 1988-2020, Bob led a whenever they are easy to use. They can
small engineering firm specializing in creating prevent eye strain, after all!
a variety of real-time embedded systems. Bob
has been awarded 11 patents in many areas STRATEGY #10: CONDITIONAL
of embedded systems and motion control. Now BREAKPOINT
retired, he enjoys building electronic projects The first time my debugger had the ability
with his grandchildren. You can reach him at to perform a breakpoint on a condition was
Bob@ListeningToGod.org. with the HP64000. I fell in love with that
feature and strongly recommend that you
invest in a debugger that gives you the ability
to break on complex expressions. The more
Additional materials from the author are available at: complex the better: not just, "Break when
www.circuitcellar.com/article-materials the variable changes," but, "Break when the
Reference [1] to [4] as marked in the article can be found there. variable is cleared for the eighth time."
circuitcellar.com 49

Although most good debuggers have this in React Native [4]. Also, pointer arithmetic has
feature now, learn how to use it to its full always been a problem for me. As we said in
capacity. You will thank me later. I'll send you an earlier article, know your enemy. Sometimes
my Venmo handle. the enemy is you. Or as Pogo said, "We have
met the enemy and he is us."
STRATEGY #11: TREAD BACKWARDS I wish I had recorded my "bug tra its" early
I'm always shocked at how hard it is to run on in my career. I would have been able to
my elliptical backward. I think (without any pick up patterns and learn from my mistakes
real evidence) this difficulty has more to do instead of repeating them. Just don't let your
with my brain than with my body. Our bodies boss see the list of bugs that you have fixed!
and our brains don't like to go backward. In
a sim ilar way, the concept of back-planning is SUMMARY
not a natural process for our brains. When I This article series has come to an end.
first learned about back-planning [3], it was Over its course, we have looked at:
a major innovation for me. Start with the end
in mind and work backward. For years, all my • the bugs that bug us (April, June, and
planning was done going forward. "Okay, we August 2022)
are here. What is the next step to get to our end • the tools needed for debugging (October
goal." Back-planning taught me to start with and December 2022)
the goal and work backward. In debugging, we • strategies for determining if the bug's in
start with the erroneous output and trace it software or hardware (February 2023)
backward to the inputs. Remember, that is not • strategies for duplicating bugs (April 2023)
the way our brains naturally think. • flawed assumptions in debugging (June
2023)
C
STRATEGY #12 : HISTORY • and now strategies for finding bugs. O
L
All of us tend to have repeat failures that U
M
plague us. I never struggled with accidentally See Circuit Cellar's Article M aterials and N
S
placing an = sign instead of a == in a C program. Resources web page for more inform ation on
(Most modern compilers help us identify those those articles. We have certainly covered a
now). But I do quite often mistake == with === lot— but, as always, only in thin slices.

UC841
Microcontroller
Design Manual ADuC841MicrocontrollerDesignManna
FromMicrocontroller Theoryto Design Projects
If you've ever wanted to design and program with the ADuC841
icrocontroller, or other microcontrollers in the 8051 family, this is the
ok for you. With introductory and advanced labs, you'll soon master the
many ways to use a microcontroller. Perfect for academics!
50 CIRCUIT CELLAR • AUGUST 2023 #397

From th e Bench

2
I C User Interface (I/O )
Button It U p ^
Almost every project that
interfaces with a user requires
some way of providing I/O to 1
the system. I add inexpensive 2/
push buttons to a low-budget y
display via an already- ,
established I2C interface, A
using an I/O expander.

S
N
M
U
L
O
C By
Jeff Bachiochi

user interface can take on many of 128 x 64 pixels. I picked up an inexpensive


forms. The light switch on the wall DIN rail enclosure, the Bud Industries
of your home handles an input task DMB-4771 (Figure 1). The top panel of this
without the need for feedback. You enclosure is 42mm x 49mm, or less than 2".
assume when you flick it up a light will go Few displays will fit in a panel this small. It
on somewhere. It could be in the same room, is most likely meant for a couple of switches,
such as a ceiling lamp, or on the other side of or maybe a connector or two. For this project
a door, such as a porch light. In a similar way, I will squeeze eight push buttons along with
outputs don't always require any input. A wall the OLED display onto a PCB that fits this
clock, for example, will happily display the enclosure.
time without the need for any input from you. The panel size for the chosen enclosure
Often, both input and output are required determines the size of the PCB for this project.
to handle a task. In a simple I/O system, Both fit into the enclosure in the same physical
pre-labeled buttons serve as fixed input space. So, we know the size of the PCB will
selections, while a display gives the user be 42mm x 49mm. Figure 2 is the schematic
prompts, or feedback, or both. I like the for the project. By using an Alcoswitch FSM
clean look of a display that has a built-in series push button from TE Connectivity, you
touchscreen. It not only removes the need for can choose from a number of stem lengths
physical input switches, but also allows the to make it work for most applications (PCB
screen touch areas to be redefined. There are to panel height). I placed four push buttons
two issues with touchscreens, though—they under the display, and two off to each side.
are generally large displays, and they can be I use the non-commercial version of the
quite expensive. Eagle Schematic and Layout program (now
This month I want to take one of the part of Fusion 360 by Autodesk). This personal­
smallest yet useful displays and add input use software has some size limitations (80cm
buttons, to make it a useful 4-wire addition x 80cm), but has been a staple in the industry
to many projects. The display I will use is the for years. A number of inexpensive PCB fab
0.96" SSD1306 OLED, which has a resolution houses cater to the hobbyist. My preference is
circuitcellar.com 51

OSH Park in Portland, Oregon. A run of three f ig ur e 1


I found this inexpensive DIN rail
PCBs costs around $5/square inch and ships
enclosure that seems like pretty
in 9-12 days. For complicated circuits, it's
good deal. It's easy to mount, has
hardly worth prototyping a circuit by hand,
cutouts for screw term inals and
especially if you wish to use the circuit in can support a number of PCBs.
more than one project.

MCP23008 I/O EXPANDER


It only makes sense to use an I2 C device
here, since the SSD1306 display is already I2 C,
meaning the interface to the microcontroller
does not change. It like getting the added
benefit of user input for free! You can see in
the block diagram of the Microchip MCP23008
(Figure 3) that this device gives the user
access to eight general purpose I/O's through
an I 2 C interface.
The ability of this device to handle bit-
defined I/O makes it very flexible, but 4 <M S W « r c

also means that several registers must be Ji


R2 ZR4 R6
1 2 4 S > .0 O
configured to determine how it will be used. IOC* lo o t

IMT U1
The default register settings configure the 8
SCI 1 18
I/O bits as all inputs, and this port can be SCA 7 SCI VDD
17 SW8
SDA GP7
sampled by reading one of the 11 registers. a : A2
Al
GPG
GP5
Ad 2 1-1 SW 1 C
For you to understand just how flexible this RST 6
AO
R IS t t
GP4
GP3
13 SW4 O
7 SW3 L
device can be, we'll need to look at all the cs GP2
sw ? U
IM GP1
10 sw M
VSS GPU
registers in the MCP23008 (Table 1). The IE DI N
R3 ZRS RZ ZR S
function of each register is summarized in i ( O > .<■» IOC* >.T MCP23S08

Table 2. Incidentally, you can get the same


device with an SPI interface (MCP23S08) for
those so inclined.
256xM
The Registers and Their Functions: Let's
begin with the registers associated with inputs. DISP SSD1306

The first register, I0DIR (address 0x00), sets


the direction of each bit. As I stated above, AG M3

the device defaults to all inputs as noted in


this register. It follows the standard used by FIGURE 2
most microcontrollers; the direction register Microchip's MCP23008 I/O expander gives you access to any combination of eight I/Os vias an I2 C
uses the format l=input and 0=output. The interface. I'm using it as eight push button inputs sharing the I2 C bus with an SSD1306 display.
second register, IPOL (address 0x01), can
invert the polarity of an input. In this case
a "0" indicates that no inversion takes place.
Let's skip to register address 0x06, GPPU.
This register can enable an internal pull-up MCP23008
(l=pull-up enabled) for any bits configured as SCL > Sena I |_ Serialized ► GPO
an input. Last, register address 0x09, GPIO, SDA « • > Interface * * Deserializer 8 • ► GP1
will reflect the present logic level of any input, ____ ___ \— "i- ----- 1 ► GP2
A2.A0 • 3 ► Decode ► GP3
with respect to the IPOL register (address G PIO
• ► GP4
0x01). | Control ____
► GP5
When using a bit as an output, the first RESET — ---------------------------------------- *1
• ► GP6
register, IODIR (address 0x00), should have INT « —t___ | Interrupt L ______
► GP7
Logic I 4 1
its corresponding bit cleared, 0=output. To
8
place a value on any bit configured as an
output, use the last register, OLAT (address POR Configuration/
0x0 A). Control
You'll note that the MCP23008 has the Registers
ability to create an interrupt. You don't have
to physically use the interrupt output to make
use of an interrupt. Although the interrupt
FIGURE 3
output can eliminate having to poll the
Block diagram of the MCP23008 I/O Expander, an I2 C device that has eight individually programmable
MCP23008 registers, you still must read the I/O. The 11 registers make it extremely flexible. An interrupt output can be used, or you can poll
appropriate registers to determine what has for a change of state.
CIRCUIT CELLAR • AUGUST 2023 #397

happened. To enable an in te rru p t on an input d iffe re n t fro m the b it in the DEFVAL reg iste r
bit, you m ust set the a ppropriate b it in reg iste r (address 0x03). This is sim ila r to generating
address 0x02, GPINTEN. How an in te rru p t is an in te rru p t on each edge, and choosing to
determ ined is dependent on the b it value in generate an in te rru p t on only one edge (or
reg iste r address 0x04, INTCON. I f the INTCON change of state).
b it= 0, an in te rru p t is generated whenever the What happens when an in te rru p t occurs?
input b it changes. I f the INTCON b it= l, an The INTF reg iste r (address 0x07) reflects the
in te rru p t is generated when the input b it is state of any and all enabled in te rru p t pins

Register Address
bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 POR/RST value
Name (hex)
IODIR 00 IO7 IO6 IO5 IO4 IO3 IO2 101 IOO 1111 1111

IPOL 01 IP7 IP6 IP5 IP4 IP3 IP2 IP1 IPO 0000 0000

GPPU 06 PU7 PU6 PU5 PU4 PU3 PU2 PU1 PUO 0000 0000

GPIO 09 GP7 GP6 GP5 GP4 GP3 GP2 GP1 GPO 0000 0000

OLAT 0A OL7 OL6 OL5 0L4 OL3 OL2 OL1 OLO 0000 0000

GPINTEN 02 GPINT7 GPINT6 GPINT5 GPINT4 GPINT3 GPINT2 GPINT1 GPINTO 0000 0000

INTCON 04 IOC7 IOC6 IOC5 IOC4 IOC3 IOC2 IOC1 IOCO -0 0 -00-

DEFVAL 03 DEF7 DEF6 DEF5 DEF4 DEF3 DEF2 DEFI DEFO 0000 0000

INTF 07 INT7 INT6 INT5 INT4 INT3 INT2 IN T I INTO 0000 0000

INTCAP 08 ICP7 ICP6 ICP5 ICP4 ICP3 ICP2 ICP1 ICPO 0000 0000

IOCON 05 — — SREAD DISSLW — ODR INTPOL — 0000 0000

TABLE 1
With these 11 registers you can program each of the eight pins as input or output. Interrupts can be generated for any logical change of state. Inputs can have
internal pull-ups enabled.

TABLE 2
The 11 registers in the MCP23008 and their functions (listed in order of discussion).
circuitcellar.com 53

that have caused the interrupt. The INTCAP


register (address 0x08) will only reflect the
first interrupt seen. Reading this register will
reset both the INTCAP and INTF registers.
If you've been keeping track (Table 2),
there is one register left, the IOCON register FIGURE 4
This 0.96" OLED SSD1306 display
at address 0x05. This register has to do with
is available with some different
four control functions. Bit 5 determines if
4-pin configurations. These are
reading more than one register at a time
also available with different screen
will auto-increment the register pointer. Bit colors. I prefer the white displays.
4 controls the slew rate on the SDA output to
help prevent noise when using slower speeds.
Bit 2 selects between open drain and push-
pull output of the interrupt output pin. And
bit 1 selects the idle logic level of the interrupt
output pin. While I am not using the interrupt
output in this project, the I2 C interface has
been laid out for 5 pins, so you can use a 4- or
5-pin connector.

A QUICK REVIEW
You've seen this used in several of my
previous projects—Adafruit's Monochrome
0.96" 128x64 OLED Graphic Display, with I2 C
C
and SPI, through 8-pins. I am using a 4-pin O
L
(I2 C only) version that I bought on Amazon. U
M
If you go this route, beware that there are N
S
a couple of different pinout offerings (see
Figure 4). You might have to rework your
cable/circuit. Other than that, they work the
same way, and the Adafruit library will handle
these.
The I 2 C address has an alternate address
that can be used if you have another device
with the same 7-bit address (0x78/7A). The
display is memory mapped, and is transferred
to the display a whole screen at a time.
Therefore, you can write different areas of
the memory at will, without worrying about
partial screen flickering, because the screen
doesn't update until you use the d is p la y .
d i s p la y O command.
FIGURE 5
Simple, pixel-based commands are
Various screenshots that show how
available with the Adafruit_SSD1306.h library.
pressing a button alters what is
With this, you can clear, invert, and display a
displayed on the screen. This gives
screen. This includes commands for get and the user an easy and efficient way
draw a pixel, draw line and screen scrolling. to move through a process.
To do some fancier graphics, including text
fonts, you will need to add the Adafruit_GFX.h
Additional materials from the author are available at:
library. This library adds commands to draw
www.circuitcellar.com/article-materials
and fill, circles, triangles, and rectangles.
Bitmaps are supported, along with text
Resources
commands that include sizing and fonts. The
Adafruit example sketch for this display really Adafruit | www.adafruit.com
shows off the use of most commands, so Arduino | arduino.cc
you can refer to it to learn how to use those
Autodesk | www.autodesk.com
commands. The default is a 5x7 character
font (6x8 including a blank right column and Bud Industries | www.budind.com
blank lower row). That's a screen width of 21
Microchip Technology | www.microchip.com
characters, and a screen height of 8 rows.
I could go through the register use and OSH Park | oshpark.com
how we can write to the display using just I2 C TE Connectivity | www.te.com
CIRCUIT CELLAR • AUGUST 2023 #397

transfers, but the complexity of this and the


H
graphic routines is beyond the scope of this
// s t a r t d e fin e MCP23008 project article. Adafruit's libraries are the best
H
and most useful functions of any libraries out
//include <Wire.h> there. Let's stick with these libraries and save
byte 12cAddress = 0x20; //0x20 column space for the device I've not used in
byte byteCount; a project up to now, the 8-bit I/O expander.
char ch a ra cte r; Let's look at a sketch to make use this new I2C
const byte menuCount = 11; peripheral.
byte byteArray[menuCount ];
const byte myDebug = 0; //1=verbose ARDUINO IDE
const S trin g menuArray[menuCount] = This user I/O peripheral can be employed
with any of the Arduino microcontrollers,
“A - Pin D ir e c tio n since it will run on 3.3V or 5V. I'll be using a
“B - Input P o la r it y Arduino MEGA 2560 for this project, because I
“C - In te rru p t En already had an I2C port wired on a prototype
“D - D e fa u lt Value shield. The first application will simply allow
“E - In t Control the user access to the MCP23008's registers,
“F - 10 Control and it starts off with some initialization for
“G - P u ll up En the expander. The menu presented comes
“H - Int Flag from m enuArray[], a list of Strings. When
“I - In t Capture the MCP23008 registers are read, the values
“J - Pin Value are stored in val ueArray [], an array of
“K - Output Latch register values. The array b y te A rra y [] is
} »
used in the I 2C functions to pass data back
in t valueArray[menuCount] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; and forth (see Listing 1).
I I k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k
As we saw back in the block diagram in
// end d e fin e MCP23008 Figure 3, there are 11 registers available to
/ / 7^ k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k
the user. This first application will exercise
those registers. A menu shows user choices
LISTING 1 and the latest values shored in those
This demo app will allow access to the MCP23008 I2C 8-bit Expander. Debug data will be sent to the registers. These are updated every time the
USB port for connection to an optional debugging serial terminal. menu is displayed. The main loop contains
only two functions, re a d A ll R e g is te r s !)
and d isp la y M e n u ().
1 1 -----------------------------------------------------------------------------
I use three functions for reading all the
// s t a r t fu n c tio n readI2C() registers. The first checks the I2C port to
I I -----------------------------------------------------------------------------
determine if its active, the second writes to
void readI2C() the port, and the third reads from the port.
The first is not necessary; its just used as
if(anybodyHome( i 2cA ddress)) a general check on any I2 C address used
(Listing 2).
if(myDebug & 1) The d isp la y M e n u () function not only
displays the m enuArray[] strings, but
Seri a l . p r i n t l n ( “ Reading these b y t e s . . . ” ); also the present values of all the MCP23008
registers. The values displayed are in binary
long i = 0; format, so you can easily see which bits (1/
if (Wi r e . r equest From ( i 2cAddress , b y te C o u n t)) Os) are in what states. The function then
waits for user input. The function will not
while (Wi r e . avai 1abl e ( )) // sla v e may send le s s than complete unless the user enters something.
requested If that something is one of the menu items
(A-K), then separate functions are called for
int c = Wi r e . re a d ( ); // re c e iv e a byte as c h a ra c te r each menu choice.
if(myDebug & 1) There are two read-only registers, H - INTF
and I - INTCAP. The other functions will let
Seri a l . p r i n t ( c , DEC); you change the register by entering a decimal
S e r ia l. p r in t ( “ , ” ) ; CONTINUED value when asked. You can actively play with
the buttons while pressing "Enter," and a new
menu displays with any updated values. Once
LISTING 2
you feel comfortable with how this device
The read and write routines make extensive use of byteCount and byteArray[] to pass all the register
works, you can move on to integrating the
data back and forth. Note the use of myDebug option to display progress or disable all debug
information. display with the expander.
circuitcellar.com 55

BUTTON/DISPLAY I/O LISTING 2 CONTINUED

Now let's add some visual output


(feedback) in a second application. Although
we can display 8 rows of 21 characters, this b y te A rra y E i ] = c ;
application will use some graphic boxes that i++;
require extra room surrounding any text, so I
won't be able to have 8 rows of text. You can
certainly get away with using no graphics, del a y (1 0 0 );
but I think you'll see it is effective for this if(m yD ebug & 1)
demonstration.
I'll skip a lot of code here, and show S e r ia l. p r in t ln ( ) ;
only bits and pieces. The complete code is
available on the Circuit Cellar Article Code and
Files webpage. I'm going to assume that the else
eight buttons have no labels on them, so I
want to use the screen to label these switches if(m yD ebug & 1)
1-8. To make it obvious what is going on,
let's display eight button-shaped boxes in S e r i a l . p r i n t l n ( “ Nobody T h e r e ! ” );
the same format as the physical switches on
the PCB: 1-4 across the bottom, and two on
each side—5-6 and 7-8. Since the screen is
128 bits wide, I can use a total of 32 bits for //
each button icon. Using a character font of // end f u n c t io n r e a d I 2 C ( )
5x7, I'll need to have a box height of 7+2+2 // C
or 11 pixels. (The characters' eighth pixel will // O
L
always be blank, so I can make use of that.) // s t a r t f u n c t io n w r it e I 2 C ( )
U
M
With a character width of 6 (including the //
N
S
blank right column) and a border of 2 on each v o id w r it e 1 2 C ()
end (one white and one black), I'll have room
for 30-2-2 or 26/6 = 4 complete characters. if(anybodyHome( i 2 c A d d re s s ))
Using these numbers, I can draw button
icons for each of the eight buttons. To help W ir e . b e g in T r a n s m is s io n ( i2 c A d d r e s s ); // t r a n s m it to
simplify this process, I use a number of arrays d e vi ce #8
(see Listing 3). The array m y P o s itio n E ] f o r ( b y t e i= 0; K b y t e C o u n t ; i++)
holds all the values necessary to feed
the d ra w R o u n d R e cta n g l e ( ) function. W ir e . w r it e ( b y t e A r r a y E i] ) ; // sends one b yte
Each icon is drawn as a border with ifCmyDebug & 1)
text from the appropriate m yLabelsE]
array, when the button is in the idle state. S e r i a l . p r i n t ( “ Wri t i ng Ox” );
When pressed, the draw function uses S e r i a l . p r i n t l n ( b y te A r r a y E i] , HEX);
the f 111 R o u n d R e c ta n g le ( ) function to
visually show that the button is pressed. The
b E n ab leE J array holds Boolean states for W ir e . e n d T ra n s m is s io n ( ) ; // s to p t r a n s m it t in g
each switch. An icon is drawn only when its if(m yD ebug & 1)
associated b E n a b le E ] bit=l.
For this second application after the S e r i a l . p r i n t ( “ F in is h e d se n d in g “ );
MCP23008 and SSD1306 have been initialized, S e r i a l . p r i n t ( b y te C o u n t);
the only thing the main loop has to do is look S e r i a l . p r i n t l n ( “ b y t e s ” );
for a change in button state, determined by
the c h e c k 4 B u tto n ( ) function. This is called
every time m i l l i s O is equal to or exceeds else
myTime, which is an offset of my Del ay
from the last time c h e c k 4 B u t t o n () was if(m yD ebug & 1)
executed. The value of my Del ay is the number
of milliseconds between button checks. In this S e r i a l . p r i n t l n ( “ Nobody There 1” );
routine, comparisons are made to determine
if a button has changed states since the last
check. The value in m y B u t t o n ln t e r r u p t s
is from the INTF register of the MCP23008. / / -----------------------------------------
Note that Listing 4 is a snippet of the test // end f u n c t io n w r it e I 2 C ( )
for button 1. The b u t t o n lP r e s s e d ( ) and / / -----------------------------------------
b u t t o n lR e le a s e d ( ) functions are where
56 CIRCUIT CELLAR • AUGUST 2023 #397

const byte m yPosition[] =

/ / / P o s itio n , y P o s itio n , w idth, height, radius


0, 52, 30, 11, 3,
32, 52, 30, 11, 3,
64, 52, 30, 11, 3,
96, 52, 30, 11, 3,
0, 0, 30, 11, 3,
0, 26, 30, 11, 3,
96, 0, 30, 11, 3,
96, 26, 30, 11, 3,
};
const Strin g my Labels El = { “ 1 “ 2 “ 3 “ 4 “ 5 “, “ 6 “ 7 “, “ 8 “ };
boolean bEnableE] = { 1, 1, 1, 1, 1, 1, 1, 1 1;

//
// s t a r t function showPushedButton(byte t )
/ / k 'A
'■A'k k ■
A’k k 'A'k k k ■
A' k k k k ■
A’k "Ar "Ar ■
A' k k k k ■
A’k "Ar
void showPushedButton(byte t )

byte p = t * 5;
d is p la y . f i 11 RoundRectCmyPosition[p], m yPosition[p+1], myPosi t i on[ p+2] 5 myPosi t i on[p+3],
m yPosition[p+4], SSD1306_WHITE);
S
N / / k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k
M
U
L // end function showPushedButtonCbyte t )
O I I k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k
C
I I k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k

I I s t a r t function showldleButton(byte t )
/ / k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k

void showldleButton( byte t )

byte p = t * 5;
di s p la y . drawRoundRectCmyPosi t i o n [p ], myPosition[p+1] , myPosition[p+2] myPosi t i on[ p+3] ,
m yPosition[p+4], SSD1306_WHITE) ;
d is p la y . setC urso r(m yPo sitio n[p ] + 2, myPosition[p+1 ] + 2 );
di s p la y . se tTe xtSi z e (1 ); // Normal 1:1 p ixel scale
di s p la y . setTextColor(SSD1306_W HITE); // Draw white te x t
di s p la y . pri nt(my L a b e ls [ t ] ) ;

end function showldleButton(byte t )

LISTING 3
The showPushedButton() or showIdleButton() functions are only called if the bEnable() array bit=1. The switch of interest, number 1-8, determines which array values
are used for the drawing functions.

i f ( ( la s t B I & 1) != (m yButtonlnterrupts & 1 ))

i f ( ( (m yButtonlnterrupts & 1) == 1) && ( ( la s t B I & 1)

b u tto n lP re sse d () ;
LISTING 4
In this snippet, we test whether
i f ( ( (m yButtonlnterrupts & 1) == 0) && ( ( la s t B I & 1)
bit 0 (button 1) of the button state
has changed and to what state it buttonlReleased( ) ;
has changed. You would then take
the necessary action based on the
change.
circuitcellar.com

you would put some code if your application


depended on this action. i f ( (m yButtonlnterrupts & 1) && bEnableEOZI)
If any change takes place, we set the // button 1 enabled
updateScreen flag so the LCD screen can { // button 1 pushed
be updated and reflect the present state of showPushedButton(O);
the buttons. The showDispl ay () function
then uses similar logic to check4Button() el se
function to determine which icon (if any) to { // button 1 id le
display (Listing 5). show ldleButton(O );
This second application merely reads
the physical buttons and reflects their state
through the labeled button icons on the LISTING 5
display. In this application, each icon can you can see the label strings that will fill In this snippet, we test whether
display 4 characters within its border. Even button icons for each of the modes. Once bit 0 (button 1) of the button state
with all 8 switches enabled, there is still the Set button is pressed in mode 0, the is pressed, and bEnable[0] array
to determine whether or not to
a central area on the OLED screen where mode changes to mode 1. Mode 1 labels will
display this icon.
you can put up to 6 lines of text. The last be displayed, and the user will chose one of
application shows how this might be used to these (DOW, Date, Time, Done).
handle time and date. Let's say we've pressed the Date button,
so the mode becomes 2. A new screen is
PUTTING IT ALL INTO PRACTICE displayed (Month, Day, Year, Done). If we
Many of my applications require a real choose "Day," the mode becomes 4, and
time clock (RTC). This often requires buttons the sub-mode becomes 2. A new screen is
to allow the user to set or change the date displayed (inc, dec, done). When the Inc or
or time. Let's put this I/O module to the test, Dec buttons are pressed, the "Day" value on
and see if we can make it usable without the the screen changes. Pressing the Done button
user referring to some manual. To keep this brings us back to mode 0. Note: Each mode
third application simple, no RTC hardware also has a b x E n a b le d f] array associated
is used. I will use the m i l l i s O timer to
increment seconds; therefore, time will be
lost when the power is removed. There are ABOUT THE AUTHOR
only basic checks on the legality of the values Jeff Bachiochi (pronounced BAH-key-AH-key)
that are incremented and decremented. This has been writing for Circuit Cellar since 1988.
is just meant to show how the buttons can be His background includes product design and
reassigned to different tasks, based on what manufacturing. You can reach him at
needs to be accomplished, and not a complete
RTC task. jeff.bachiochi@imaginethatnow.com, or at:
I've defined some arrays that can be www.imaginethatnow.com.
switched in and out. There are five modes;

String myLabelsEl = {“ 0 , “ 2 “, “ 3 “, “ 4 “, “ 5 “, “ 6 “, “ 7 “I
ii ii t(

> 9

const String modeOLabelsEZ {“


ii it
9
ti ii
9
it
“ s e t” ,
ti
9
ii ii
9
ii ti
9
ii

const String modelLabelsEZ {“ DOW” , “ Date” , “Ti me” , “done” , ii ii


9
ii ii
9
ii ii
9
ii

const String mode2LabelsEZ {“ mon” , “ day” , “ yr “ , “done” , ii ii


9
ii ii
9
ii ii
9
ii

const String mode3LabelsEZ {“ hr “ , “ min” , “ sec” , “done” , ii ii


9
ii it
9
ii it
9
ii

const String mode4LabelsEZ {“


it
“done” ,
ii
9
ii
i nc ,
it
9 dec , 4 _ 99 ii _| _ _ 99 ii it
9
ii

boolean bEnablef] = { 1, 1, 1, 1, 1, 1, 1, 1 };
const boolean bOEnablef] = { 0, 0, 0, 0, 0, 0, 1, 0 };
const boolean blEnablef] = { 1, 1, 1, 1, 0, 0, 0, 0 };
const boolean b2Enable[] = { 1, 1, 1, 1, 0, 0, 0, 0 };
const boolean b3Enable[] = { 1, 1, 1, 1, 0, 0, 0, 0 };
const boolean b4Enable[] = { 0 , 0 , 0, 1, 1, 1, 0, 0 };
boolean tEnableEJ = { 0, 0, 0, 0, 0, 0};
const String arrayD0WE7] =
{“Sunday” , ’’Monday” , ’’Tuesday” , ’’Wednesday” , ’’Thursday” , ’’ Frid ay” , ’’Saturday” };
const String arraySet[7] = {“ set DOW” , ’’set Month” , ’’set Day” , ’’ set Year” , ’’set Hour” , ’’set
Minute” , ’’set Second” };

LISTING 6
Here we see the arrays that have been added to handle different screen modes. When you have selected a variable to set, an extra line of text is added to the screen
to indicate which one you are changing. You can see a few actual screens in Figure 5.
58 CIRCUIT CELLAR • AUGUST 2023 #397

with it. It controls which buttons (icons) are


I Ikkkkkkkk k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k
displayed. Only displayed buttons are active.
II s t a r t f u n c t io n b u tto n 5 R e le a s e d ( ) Actual screens are shown in Figure 5.
I Ikkkkkkkk k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k
When a button is pressed or released,
v o id b u tto n 5 R e le a s e d ( ) we can do four things: change the mode,
change the sub-mode, operate on a value,
S e r i a l . p r i n t l n ( “ B u tto n 5 R e le a s e d ” ); or do nothing. Depending on the mode, we
if(m o d e == 4) need to display a different set of buttons. This
is accomplished by transferring a particular
s w it c h ( submode) / / in c re m e n t set of arrays of constants (Listing 6) into
m yLa b elsLJ and b En ab leEJ which are
case 0: / / DOW
used in the display routine. Once in mode 4,
dow++;
the display shows the Inc and Dec buttons.
if( d o w >= 8)
We've just come from choosing one of seven
variables. To remind the users what sub-mode
dow = 1;
they have chosen, a new line of text, from
b re a k ; a r r a y S e tE ] , is displayed on the screen.
case 1: / / month The present DOW, Date, and Time are
month++; always shown in the center of the screen.
if(m o n th >= 13) When the Inc and Dec buttons are used,
the chosen variable is updated and will be
month = 1; displayed live. When the present variable has
been adjusted, the Done button changes the
b re a k ; mode to 0, which brings the application to the
S case 2: / / day idle screen (Listing 7).
N
M
U
day++;
L
O if ( d a y >= 32) THE END
C Although this brings this project to a chose,
day = 1; it is only the beginning of where you might take
this in one of your own applications. Whether you
b re a k ; replicate this PCB or incorporate its components
case 3: // year into your own circuit, I think you may find this
year++; will handle most situations where you need
b re a k ; some user feed back for specific tasks. This
case 4: / / hour project was conceived to provide some required
hour++; user I/O in a modular fashion at a minimal cost.
if ( h o u r >= 24) I wish I had done this years ago. It would have
saved countless hours.
hour = 0; You may have noticed that there is an LED
tied to the interrupt output of the MCP23008.
b re a k ; This was used as an indication of a button
case 5: / / m inute press. I think a piezo device could be used
mi nute++; here to provide audible feedback when a
if ( m in u t e >= 60) button is pressed. An interrupt is cleared
when the INTCAP or GPIO registers are read.
m in ute = 0;
It may be of interest to note that I tossed
around the idea of using a m icrocontroller on
b re a k ;
this PCB to handle the button inputs. This
case 6: / / second
could have been handled as a remote I2 C
second++;
device, but the cost of the MCP23008 was only
if ( s e c o n d >= 60)
about a buck and a half and required no
programming. With too much to do, and so
second = 0;
little time, I chose to use the I/O expander.
b re a k ;

LISTING 7
In application 2 we saw how pressing and releasing any
u p d a te S cre e n = t r u e ;
button called a function. In this third application, we see
I Ikkkkkkkk k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k
what happens with the release of button 5. We only want
do something if the present mode = 4. In this mode, the
II end f u n c t io n b u tto n 5 R e le a s e d ( ) button icon is labeled Inc. Depending on the sub-mode
/ /k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k k
value, which was set in a previous mode, we will increment
one of seven variables.
circuitcellar.com 59

PRODUCT NEWS by Stephen Vicinanza

An Affordable Arm Cortex-MO+ MCU Portfolio


Texas Instruments released a new Arm Cortex-M0+ current requirements and plan for future designs.
microcontroller (MCU) portfolio aimed at affordability: the In this family, TI plans to release over 100 MCUs this year
MSPMO MCU family. The industry-low pricing of these 32-bit alone. The company aims to be the most comprehensive
general-purpose MCUs from TI starts at $0.39. source of affordable, general-purpose 32-bit MCUs.
The launch in March saw dozens of MCUs supported by "TI is building the industry's most comprehensive portfolio
intuitive software. There were also design tools that allowed of Arm Cortex-M0+ based MCUs—expanding an already
developers to spend more time innovating, and less time extensive semiconductor offering with options for general-
evaluating and coding, when using one of these devices. purpose designs," said Vinay Agarwal, Vice President of MSP
Overall, the new designs promise to cut months out of design Microcontrollers, Texas Instruments. "Our new MCUs provide
time. the flexibility our customers need to enhance the sensing and
Designers can choose from control capabilities of their systems
a range of computing options, while cutting cost, complexity, and
from 32MHz up to 80MHz, with design time."
math acceleration and multiple
configurations of integrated analog Texas Instruments | TI.com
signal-chain components. This
includes the industry's first zero­
drift operational amplifier on an
MCU, and precision 12-bit, 4-MSPS
analog-to-digital converters. That
flexibility helps designers meet

Qualcomm's Aware Platform and Four New loT Devices


In February Qualcomm presented its Aware Platform API-first design, with ease of use indicates a suite of APIs,
with four new Internet-of-Things (loT) devices—a line of webhooks, and development tools with integration abilities
P
trackers and sensors that all fit into the company's new for private cloud and enterprise resource planning (ERP). R
O
Aware Platform, an end-to-end loT system. Qualcomm touts This makes digitization quick and easy for deployments while D
U
three pillars upholding Aware: industry-leading technology, being cost-effective and still delivering better performance. C
T
an expansive hardware ecosystem, and easy-to-use, API-first The real core of this platform is the use of the latest N
E
design. sensors, trackers, and a smart label. The four devices make W
S
Industry-leading technology means a proprietary set of up a hard-to-beat system when backed by Qualcomm's years
positioning techniques, advanced silicon, and connectivity of experience in the industry and beyond. The device lineup
solutions. The set offers developers a complete package that includes:
is intelligent and optimized for cloud design and enterprise
across multiple industries. • Aware Sensor, a low-cost, ultra-compact inclinometer
The expansive hardware ecosystem includes a broad used for pole tilt monitoring. The sensor is cloud-
range of partner companies that deliver software and attached, reports on the tilt of the assets, and sets off an
hardware to enterprise-scale developers. The developers can alarm if a title threshold is reached or exceeded. It can
work faster and more cost-efficiently in developing connected report on impact thresholds as well.
solutions. Integration with the cloud is seamless, and users • Aware Cellular Label, a peel-off smart label that attaches
can manage devices and services effectively and with ease. right to the box and tracks shipments. It periodically
reports the location of the asset to the cloud and can set
off an alarm if the package is breached or opened.
• Aware Tracker, a smart device with a long list of sensor
capabilities. It can track location and environmental
conditions, and also detect falls, temperature, and
humidity, among other abilities.
• Aware Thin Tracker, a credit card-sized tracker designed
for visibility and shipment logistics. It's reusable,
chargeable, and power-optimized for efficiency. It's also
lightweight and can transmit geolocation data to the
cloud.

Qualcomm | qualcomm.com

NEW PRODUCT SUBMISSIONS— E-mail: product-editor@circuitcellar.com


60 CIRCUIT CELLAR • AUGUST 2023 #397

Feather Board with Two USB Ports


Dev boards with a single USB port are common— but how They found this is an acceptable workaround, working just as
about two? Adafruit's Feather RP2040 board has both a USB well as any MCU USB host peripherals.
Type-A host and a Type-C port. The recommended library, including for the Pico SDK, is
It doesn't come with two USB sekigon on GitHub.
port peripherals, but does have a PIO The Feather runs an RP2040 chip at up
peripheral that can be used to emulate to 133MHz and 3.3V logic. This is the same
a USB host peripheral. The main USB chip used in the Raspberry Pi Pico. There is
port is still active for uploading, data a large 8MB onboard QSPI Flash and 264K
communication, and debugging, while of RAM. There is also room for a STEMMA
at the same time sending and receiving QT connector for plug and play I2 C devices.
data to just about any USB device.
Adafruit lets everyone know upfront Adafruit | adafruit.com
that this is a firmware hack. The second
Arm core and both PIO Peripherals need
to be dedicated to handle USB messages.

Software That Gives Developers Freedom of Choice


NXP Semiconductors' recently announced MCUXpresso for FreeRTOS.
suite of software's designed to give developers more freedom There is also a MIPI DSI driver improvement, and fixes for
in choosing IDEs to accompany their MCUs. i.MX RT1170, as well as updates to multicore examples and
The MCUXpresso works with several NXP partners, MISRA enhancements for the i.MX RT1170.
including IAR and Arm Keil, to develop the product family. The MCUXpresso IDE has a host of exciting features.
The core technology includes the open-source MCUXpresso The underlying tool and host OS support updates include
Software Development Kit (SDK), designed specifically for Migration to Eclipse 2022.06, host OS support for MacOS
processor and evaluation board selection. 11/12, Ubuntu 20.04 2/22.04 LTS, and Windows 10/11.
The software suite includes an RTOS abstraction layer for There is also now an Open CMSIS pack preview support
networking and Cloud/OTA for Wi-Fi. Initially, support will be (pack import) and a boot pin configuration and control feature.
The configuration tools vl3.0 for the MCUXpresso include
S Zephyr support for pins, which generates the pin mixing
W configuration in the Zephyr Device tree format. There is also
E
N initial support for i.MX RT1060, LPC55S69 and FRDM-K64.
T
C The suite also includes access to IAR's Embedded
U
D Workbench and Arm Keil IDEs for even more freedom for
O
R developers. It's a comprehensive gathering of toolsets that
P
offers designer flexibility and ease of use across many
spectrums of development. It can be applied to industrial
or consumer device designs and offers a large number of
examples in the demos.

NXP Semiconductor | nxp.com


Queppelin | queppelin.com

Ultra-Low-Power Accelerometer with Anti-Aliasing and Al


STM LIS2DUX12 is an ultra-low-power accelerometer with of system integrations. This is from the point of view of the
anti-aliasing and A L Although released in November 2022, bill of materials, power consumption, and processing.
the LIS2DUX12 from STMicroelectronics was just showcased The accelerometer has a dedicated internal engine to
at Sensors Converge 2023. process motion and acceleration detection including free-fall,
The device is a smart, digital, 3-axis linear accelerometer single/double/triple-tap recognition, activity/inactivity, wake­
whose MEMS and ASIC have been expressly designed for the up, and 6D/4D orientation.
lowest power consumption. Features include always-on anti­ The LIS2DUX12 has full scales of
aliasing filtering, a finite state machine (FSM), and a machine ±2g/±4g/±8g/±16g, selectable by the
learning core (MLC) that has an adaptive self-configuration user. It can also measure acceleration
(ASC). with output data rates from 1.6Hz to
The FSM and MLC with ASC offer always-on, edge 800Hz.
processing capabilities. The sensor's MIPI I3 C remote
interface and embedded 128-level FIFO buffer complete a set STMicroelectronics | st.com
of features that make the accelerometer a reference in terms

NEW PRODUCT SUBMISSIONS— E-mail: product-editor@circuitcellar.com


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.

For current rates, deadlines, and more information contact


Hugh Heinsohn at 757-525-3677 or Hugh@circuitcellar.com.

CCSLOAD Update
Version 5.075: 8-bit AVR® Support

Programming support for all 8-bit


AVR® microcontrollers
*HVSP interface is not supported. Update o f CCSLOAD software required

CCS programmers supported:


Prime8, LOAD-n-GO, ICD-U80, and Mach X

8-bit AVR® adapter and supporting


cables available for purchase
Sales@ccsinfo.com
(262)-522-6500 Ext. 35
www.ccsinfo.com/cc222
AVR® is a registered trademark o f Microchip Technology Inc.

www.embeddedARM.com

TS-7100
NXP i.MX 6UL 696 MHz ARM CPU w ith FPU
Our smallest single board com puter

Technologic
CIRCUIT CELLAR. • AUGUST 2023 #397

TEST YOUR EQ Contributed by David Tweed


Answer 1—The full adder is a logic element that has three
inputs and two outputs. The outputs, "carry" and "sum" Answer 3—Three 4-input LUTs can count the number of
represent in binary how many of the three inputs ("a", "b" ones in 4 bits, each LUT producing 1 bit of the 3-bit result.
and "carry in") are one. It takes two LUTs to create a full adder (one for each of the
output bits), so six additional LUTs are required to add the
Answer 2—Take two full results of two 4-bit counters together, for a total of 3 + 3 +
adders, each counting 3 6 = 12 LUTs.
bits, and add their outputs Note that, like before, the second-stage adder has an
together using two more unused carry input, so the circuit can actually count the ones
full adders. The output will in a total of 9 input bits.
now be 3 bits wide. Note
that there's another "carry Answer 4— In general, tree structures like those we're
in" input that can be used to count a 7th input bit. So this building here tend to have linear space requirements; in
circuit can count 7 inputs, providing a 3-bit binary output. other words, the complexity is O(N) on the number of input
This concept can bits. Let's confirm that:
be used repeatedly
to build larger For the full adders: For the LUTs:
Inputs Adders Ratio Inputs LUTs Ratio
ones counters. For
3 1 0.333 4 3 0.75
example, combine
7 4 0.571 9 12 1.333
the outputs of two
15 11 0.733 19 32 1.684
7-bit counters with 31 26 0.839 39 74 1.897
three more full
63 57 0.905 79 160 2.025
adders to count a
127 120 0.945 159 334 2.101
total of 15 inputs,
giving a 4-bit In each case, the ratio of circuit elements to inputs starts
result. small and grows, but it asymptotically approaches a limit that
it will never exceed. For the full adders, that limit is 1.000,
and for the LUTs, it's 2.200.

Connect with
Confidence
Partnering with Digi for your loT
project can deliver exceptional ROI -
from critical insights to cost reductions

Dig* ConnectCcre is very small and power-efficient, so it


fits nicely in our device. We received extraordinary technical
support from the Digi team. We‘re very pleased to have a
successful long-term relationship with Digi.n
Adity.i Banial, Kinetic Co Icundet and CTO

As Wi Fi has gamed momentum in healthcare, we


quickly shifted our designs to connect wirelessly, which
hospitals prefer for reasons of security and convenience.
JU we've transitioned Dig* has been right there with us.n
Ned Buttington, Avancen Chief Executive Officer

We created a privacy platform so patients can securely


access and provide sensitive healthcare data without
using a smartphone or the Internet in a way that
completely meets legal requirements?'
DiHe# Rlttingef. DeGtV Founder jn d CEO

www.circuitcellar.com/digi
circuitcellar.com 63

Tools Best Suited For Its


Unique Requirements

n the not-so-distant past, anyone m icroprocessors and m icrocontrollers—


wishing to design and develop something developed their own proprietary IDEs.
new was typically obliged to create These typically shared many of the same
every aspect of the system. A classic disadvantages, most of which derived from
example is provided by H. Joseph Gerber, who the fact that the vendors were focused on
survived the Holocaust and arrived penniless selling silicon, so they made these IDEs
in America with his mother in 1940. Aged available for a low cost or for free. As a
16, with little English, Gerber fought his way result, the underlying tools, like compilers,
through a four-year high school curriculum often generated less than optimal results by
in just two years and obtained a BSc degree failing to optimize code to its fullest extent.
in Aeronautical Engineering in just two more Furthermore, users found themselves locked
By
years. into whatever fam ily or fam ilies of processors
Gerber revolutionized many aspects of were supported by the IDE. Rafael Taubinger
American industry in various fields, including A more recent IDE concept is epitomized Sr. Product Marketing
engineering, electronics, printing, apparel, by the open-source Eclipse IDE, which
and aerospace. When Gerber turned his contains a base workspace and an extensible Manager, IAR
attention to creating printed circuit boards plug-in system for customizing the
(PCBs), for example, in addition to having environment. Eclipse is written mostly in Java
to design and build his own digital plotters and is prim arily used for developing Java
and photo-plotters, he also had to define the applications. However, it may also be used to
data form at used to store the PCB files. The develop applications in other programming
resulting Gerber form at remains the de facto languages via plug-ins, where these languages
standard used by PCB industry software to include C, C++, C#, and Python. Although it has
this day. grown in popularity since its initial release in
By comparison, today's inventors can 2001, many users feel that the Eclipse IDE has
avail themselves of a vast ecosystem and evolved to be "bloated," "heavy," and harder
infrastructure, leaving them free to focus to use than one might hope.
their attention on the "secret sauce" that will
differentiate their creations from competitive
offerings. In many respects, the same story
is currently unfolding with respect to the
tools used to develop code for embedded
applications.

INTEGRATED DEVELOPMENT
ENVIRONMENTS
An integrated development environment
(IDE) is a software application that acts as
a "command-and-control center" for all the
tools required by computer program m ers
for software development. In addition to a
source code editor, compiler (or interpreter),
and build automation tools, professional IDEs
also include analysis (for example, static code
analysis) and debugging tools.
Circa the latter part of the 20th century,
many processor vendors—including f igur e 1
Modern workflows span the desktop to DevOps.
64 CIRCUIT CELLAR • AUGUST 2023 #397

VISUAL STUDIO CODE especially in the context of debugging, which


Created by Microsoft, Visual Studio Code, presents its own unique challenges.
commonly referred to as VS Code, is a IAR is one of the leading vendors of
source code editor that also acts as an IDE. development tools for embedded systems.
It inherently supports features for tasks like When Microsoft had questions about
debugging, syntax highlighting, intelligent debugging in the embedded domain, they
code completion, snippets, code refactoring, came to IAR for advice. IAR has its own IDE
and embedded Git. called IAR Embedded Workbench. In addition
VS Code is fast, lightweight, easy to use, to its source code editor, IAR Embedded
popular, and considered by many to set the Workbench also features a state-of-the-art C/
"gold standard" for IDEs. In fact, in a 2022 C++ compiler that offers advanced global and
Developer Survey by Stack Overflow, VS target-specific optimizations and supports a
Code was ranked the most popular developer wide range of industry-standard debug and
environment tool among 71,010 respondents, image formats. Related tools include the
with 74.48% reporting using it [1]. Of IAR C-STAT static analyzer, the IAR C-SPY
particular interest to many employers is that debugger—which includes a comprehensive
today's college and university graduates are macro system that facilitates automating
increasingly familiar with VS Code. the debugging process and simulating
As a source-code editor, VS Code can be peripheral devices—and IAR Build Tools that
used with various programming languages, provide automated application build and test
including C, C#, C++, Fortran, Go, Java, processes.
JavaScript, Node.js, Python, and Rust. VS Now, IAR has made its official VS Code
Code also supports a wide selection of plug­ extensions for the IAR C/C++ compiler, IAR
in extensions that provide access to tools C-STAT static analyzer, IAR C-SPY debugger,
from third-party vendors. These tools include and IAR Build Tools available in the Visual
compilers, interpreters, code checkers, Studio Marketplace.
debuggers, builders, and tools that allow
users to quickly integrate into continuous WELCOME TO THE FUTURE
integration/continuous delivery (CI/CD) Today's embedded code development
pipelines. involves teams of all sizes, from individuals
At a traditional programming level, VS working in isolation to large multinational
Code can provide a unified frontend for use teams scattered across the globe. Today's
with projects that require access to disparate embedded systems range from small
tools "under the hood." VS Code also satisfies microcontroller-based devices to sophisticated
the requirements of projects involving large artificial intelligence-powered systems. And
numbers of developers dispersed around the today's embedded code developers refuse
world. to be locked into proprietary tools and
development environments.
VS CODE MEETS IAR Developers of the future will demand the
As was previously noted, VS Code supports ability to use tools that best satisfy their
a wide selection of plug-in extensions that own unique requirements. These tools will
provide access to tools from third-party be designed to take full advantage of modern
vendors. Easy access to these extensions workflows, including access to Git, the GitLab
is provided from Microsoft's Visual Studio DevSecOps platform, and the Jenkins open-
Marketplace, which can be accessed from source automation server—also, tools that
within VS Code. support containerization and cloud-based
Although VS Code is well-respected builds (Figure 1).
regarding the tools available for developing Welcome to the future! Because this is
applications for markets like mobile, the web, available here and now with tools like VS Code
and the cloud, its capabilities in the embedded that allow users to employ best-in-class
domain leave something to be desired, extensions such as those provided by IAR.

Additional materials from the author are available at: ABOUT THE AUTHOR
www.circuitcellar.com/article-materials Rafael Taubinger has been with IAR for more than 15
Reference [1] as marked in the article can be found there. years. He is the company's Senior Product Marketing
Manager. He can be reached on Linkedln or via the

RESOURCES IAR website.

IAR Systems | www.iar.com


©TDK

pPOL™ Chip-Embedded
Power Modules
A Simple Solution for High Power Density Applications

TDK pPOL™ DC-DC converters are compact and highly integrated


point-of-load converters for powering CPUs, MCUs, ASICs, FPGAs,
DSP, and other advanced digital logic devices, providing the high
performance, fast load transient response, and high accuracy voltage
regulation needed by these devices.

Technology Includes Inductor, DC-DC regulator with MOSFETs and Driver

Ultrathin: 3.3 mm x 3.3 mm x 1.5 mm or 4.9 mm x 5.8 mm x 1.6 mm

Plug & Play (No Compensation Required)

DC-DC Analog & Digital Bus Options (I2C / PMBus)

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)
GO BUILD I f Powered by the NXP LMX6 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.

3 8 0 0 MHz Solo or 1 GHz Quad Core Arm based CPU

to 2 GB DDR3 RAM

3 4 G B M L C e M M C Flash

TS-7970 3 S A T A II, MiniCard, DIO, ADC, ModBus, USB, CAN


NXP i.MX6 Arm® Cortex®-A9 ARM CPU
^ M u ltim e d ia Solution w ith HDMI, LVDS, and A udio I/O
Single Board Computer

* ^ M a d e in USA
h L ^ * w it h Global Parts ssembeddedTS

You might also like