Professional Documents
Culture Documents
Circuit_Cellar_-_August_2023
Circuit_Cellar_-_August_2023
AUGUST 2023
c irc u itc e lla r.c o m ISSUE 397
I Application-Specific MCUs
nun linn ■m
2 CIRCUIT CELLAR • AUGUST 2023 #397
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.
OUR NETWORK
circuit cellar
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
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
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 *
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;
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
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
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
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
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:
Optional properties:
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
S
P a D e t e c t i o n and Detejmence
E
R
U
T
A
E
F
Raul Alvarez-Torrico
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
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.
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
HTML code for the webpage shown in Figure Object detection sub-system.
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. }
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
4 II II
By
Michael Lynes
E
R
U
T
A
E
F
H
C
E
T
FIGURE 2
Some UAV Form Factors (Source:
The Multidisciplinary Digital
Publishing Institute MDPI [4])
26 CIRCUIT CELLAR • AUGUST 2023 #397
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.
Resources
Airborne Studios | airborn-studios.com DSLRPros | www.dslrpros.com
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.
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
• NEXT MONTH'S TOPIC: Power/Battery Management Send related product announcements to editor@circuitcellar.com
circuitcellar.com 33
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:
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:
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:
gw
woseph Corleto
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
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
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
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:
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.
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.
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
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
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
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
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
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
//
// 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
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 ] ) ;
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.
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
String myLabelsEl = {“ 0 , “ 2 “, “ 3 “, “ 4 “, “ 5 “, “ 6 “, “ 7 “I
ii ii t(
•
> 9
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
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
Qualcomm | qualcomm.com
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.
CCSLOAD Update
Version 5.075: 8-bit AVR® Support
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
Connect with
Confidence
Partnering with Digi for your loT
project can deliver exceptional ROI -
from critical insights to cost reductions
www.circuitcellar.com/digi
circuitcellar.com 63
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
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
pPOL™ Chip-Embedded
Power Modules
A Simple Solution for High Power Density Applications
Current Output: 3 A, 4 A, 6 A, 12 A
REGISTER FOR
Wide Input Voltage (up to 16 V) A FREE pPOL
EVALUATION
Adjustable Vout ±5m V
BOARD
Output Voltage, ±0.5% Initial accuracy (Up to 5 winners)
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.
to 2 GB DDR3 RAM
3 4 G B M L C e M M C Flash
* ^ M a d e in USA
h L ^ * w it h Global Parts ssembeddedTS