Circuit Cellar - April 2023
Circuit Cellar - April 2023
APRIL 2023
c irc u itc e lla r.c o m ISSUE 393
SENSORS
INTEGRATION AND DEVELOPMENT
nun linn ■m
CIRCUIT CELLAR • APRIL 2023 #393
The Sky Might Be Falling, Soonish $50, Canada $65, Foreign/ ROW $75. All subscription orders
payable in US funds only via Visa, MasterCard, international
postal money order, or check drawn on US bank.
B
SUBSCRIPTION MANAGEMENT
(Al) chatbot, will have been available to the public for at least four
months. By today's standards, that could well mean it's already old Online Account Management: circuitcellar.com/account
Renew | Change Address/E-mail | Check Status
hat—especially if the robot uprising has already taken place. (And, if
that is the case, my compliments to our new robot overlords for their efficiency!) CUSTOMER SERVICE
But as I write this, ChatGPT is still the talk of the town. To most observers, both
E-mail: [email protected]
expert and non-, it seems to be a bellwether of what's to come.
Phone: 434.533.0246
Reports in February that researchers with the KTH Royal Institute of Technology
Mail: Circuit Cellar, PO Box 417, Chase City, VA 23924
used recursive training Al to "crack" the National Institute of Standards and
Technology (NIST)-recommended CRYSTALS-Kyber post-quantum encryption Postmaster: Send address changes to
algorithm have since been challenged as a misleading distraction—by none other Circuit Cellar, PO Box 417, Chase City, VA 23924
will address new or coming-soon cyber threats to embedded systems. Multiple Phone: 757-525-3677
sources cite "security" as the most dominant focus for embedded design Fax: 888-980-1303
in 2023. And, in other news that certainly will be old hat soon, the Biden E-mail: [email protected]
Advertising rates and terms available on request.
administration recently announced a national cybersecurity strategy that shifts
more responsibility for cybersecurity onto tech firms. I'm sure some of our
NEW PRODUCTS
readers are involved in security-related projects right now, perhaps nodding
enthusiastically from their seats as they thumb this issue's pages. If that's the E-mail: [email protected]
consumption (see "A Power Consumption Monitor for loT Boards," Circuit Cellar
Entire contents copyright © 2023 by KCK Media Corp.
392, March 2023) when he was asked to review the JS220. In his Start to Finish All rights reserved. Circuit Cellar is a registered tradem ark
column, Stuart Ball discusses biometrics in embedded projects and examines of KCK Media Corp. Reproduction of this publication in
whole or in part without written consent from
the example of a particular fingerprint sensor. From his corner of the Magic KCK Media Corp, is prohibited.
Smoke Factory, Joseph Corleto explains thermistors and how to use them. In
Embedded in Thin Slices, Bob Japenga continues his long-running series on
DISCLAIMER
debugging embedded real-time systems with a piece detailing strategies for
duplicating bugs. Also, Pedro Bertoleti breaks down using FreeRTOS with an KCK Media Corp, makes no warranties and assumes no
Arduino, and Avian Marinakis shares the details of a vintage-style tube amp built responsibility or liability of any kind for errors in these
programs or schematics or for the consequences of any such
with an ADAU1701 audio system chip and an ESP32. Plus, I round up nine new errors printed in Circuit Cellar®. Furthermore, because of
32-bit microcontrollers in this month's Datasheet, and Steve Prescott reports on possible variation in the quality and condition of materials and
the latest tech at the 2023 World Ag Expo in workmanship of reader-assembled projects, KCK Media Corp,
disclaims any responsibility for the safe and proper function
Product News. of reader-assembled projects based upon or from plans,
It's a thrilling, if hair-raising, time in 9 descriptions, or information published in Circuit Cellar®.
embedded electronics. I look forward to more r
The information provided in Circuit Cellar® by KCK Media
excitement in next month's issue (assuming & Corp, is for educational purposes. KCK Media Corp, makes
an Al algorithm has not taken my job by no claims or warrants that readers have a right to build
things based upon these ideas under patent or other
then). Until then. z relevant intellectual property law in their jurisdiction, or
that readers have a right to construct or operate any of
the devices described herein under the relevant patent or
other intellectual property law of the reader's jurisdiction.
The reader assumes any risk of infringement liability for
constructing or operating such devices.
OUR NETWORK
Joulescope JS220
A Precision
DC Energy Analyzer
S
E
R
U
T By
A
E Brian Millier
F
measurements as well.
was lucky enough to be asked to review The 2x5 pin socket provides various
I
the new Joulescope JS220 instrument general-purpose digital inputs and outputs
by the manufacturer Jetperch. This which can be used to synchronize the unit's
instrument pushes the boundaries of measurements to events happening during
the current or power measurements that the target microcontroller's (MCU's) code
I encounter with my projects. Measuring execution. The Trigger BNC can be configured
the power consumption of battery-operated as an input or an output and can similarly
loT projects is fairly challenging for the synchronize other instruments or the target
conventional instruments that I own, but is MCU itself.
easily handled by the wide dynamic current The JS220 is completely controlled by
range of the Joulescope JS220. the attached PC computer, and all the data
Figure 1 is a photo of the JS220 instrument it collects is immediately streamed to the PC
itself. It comes in a nice padded carrying over USB. Jetperch supplies a user interface
case, and its packaging would make for a program for the PC. This application, which
great "unboxing" video. You can see that it I'll refer to as the Joulescope user interface
is a small unit from the relative size of the (UI), will run under Windows, Mac OS, or
extruded aluminum enclosure compared Ubuntu Linux. It's freely distributed, and can
to the banana jacks. There are two sets of also be installed on other (off-line) computers
inputs: voltage (black and red) and current in order to fully analyze the data-logging files
(red and yellow). The unit uses USB for power that the Joulescope produces.
and to transfer its data to a PC. If you have experience measuring currents,
Figure 2 shows the rear panel of the you'll know that it's often important that the
instrument. It contains a USB-C socket but current-measuring device be floating. That
comes with a USB-C to USB-A cable. Its power is, it should not be referenced to ground, or
requirements are less than 500mA—the anything else, for that matter. The JS220 fits
maximum provided by USB-A. that criterion. Its entire analog front end, ADC,
and the control/processing FPGA are isolated
from its USB circuitry (which is inherently
ground-referenced via its connection to the
host computer). Figure 3 shows the rough
location of the isolation barrier on the bottom
of the JS220's printed circuit board (PCB).
Notice the precious metal plating on the edges
of the PCB—this ensures good contact with
the enclosure for shielding purposes.
Another important consideration in current
FIGURE 2
measurements is what's called the "burden
This is the JS220's rear panel configuration. It communicates with a PC and is powered by it via the voltage." This is the voltage that is dropped
USB-C socket in the center. The 10-pin socket to the left provides access to several GPIO pins, which can across the measuring device when the full-
be used to synchronize the unit's measurements with other instruments. scale current is flowing through it. With the
circuitcellar.com
JS220's wide current measuring range, this the install file from the Joulescope website.
burden voltage could be a deal-breaker. The install file is a 48MB EXE file that contains
Jetperch solves this issue by incorporating all the necessary files to install the Joulescope
a multi-section shunt resistor chain. Which program; in other words, it's not just a stub
sections of this shunt resistor are actually that downloads everything from the internet.
placed across the current input terminals is Unlike many applications that connect
electronically selected, under FPGA control, to an external device, the Joulescope
to match the current range being measured. application doesn't need to be configured for
This results in a maximum burden voltage of the Joulescope JS220. That is, the JS220 is
25mV at 1A. On the highest current range, not configured as a USB CDC device, so you
the shunt resistor is 0.01Q. This increases don't have to play around with a COM port
proportionally, on each range, to a maximum selection to make it work. Instead, once it's
of 1,1110 on the 18pA range. In Section 7.5 in plugged into the USB port, the Joulescope UI
the User's Guide, you can see, from the values
listed, that the shunt resistor is actually a
chain of resistors in series.
Table 1 lists some of the important features
and specifications. It has a wide, bipolar input
range for current and voltage measurements.
It synchronously measures both voltage and
current using a 16-bit ADC at a sampling rate
of 2 million samples/sec. The JS220 contains
an internal MOSFET switch that can switch
the current flowing through the Current-l
and Current- terminals. This will allow you to
measure inrush currents at startup. Within
the stated voltage range, the voltage input
and current inputs are isolated with respect
to each other. So, you can use either low-
side or high-side current measurements. The
voltage input is completely floating. If you
wish to take only voltage measurements, you FIGURE 3
must connect a jumper between the positive This is a view of the PCB inside the JS220. The ground-referenced USB circuitry is on the left. To the
voltage terminal and the positive current right, and separated by an isolation barrier on the PCB, is the AFE, ADC and FPGA signal processor. This
terminal. I know from experience— if you is floating with respect to mains ground.
it's collecting data, you can click on the X-Axis icons and adjust open the Joulescope UI application. So, when you click on one
the horizontal timescale to provide a useful display. of these files, it will invoke a new instance of the Joulescope
Adjusting the Y-Axis display (current, voltage, power) program and then load the captured data stream. You are
manually is a bit less intuitive. If you click in the Y-Axis label then free to scroll and zoom the scaling of the display axes,
area (current or voltage) you get a menu. Among the choices is just as you would do with the Joulescope UI while it was
Range. If you set this to Manual, you can then adjust the display connected to a JS220 and acquiring data. You can also add
magnification of that waveform using the mouse scroll-wheel, m arkers and scroll them around to see the voltage and current
while the Y-Axis labels have the mouse focus. You can also toggle data at any given time. The filename itself contains the actual
the display between a linear or logarithmic representation. calendar data and the time (hh:mm:ss UTC) that the data was
The JS220 is acquiring data simultaneously for both collected. More information about this file structure and its
voltage and current at a rate of 2 million samples/sec. Most capabilities can be found at the Joulescope Github URL [1].
of the time, obviously, you don't expect to be seeing each of Since the Joulescope UI program is freely available to
these samples on the screen—about one m illisecond's worth anyone, such JLS files could easily be sent to others for
of samples would fill up a normal flat-screen monitor. analysis—whether they had a JS220 unit on hand or not. I
Instead, the Joulescope application shows the average of was impressed by this Joulescope feature.
many samples, using a yellow trace. The actual number of There is also a rectangular blue icon in the control toolbar
samples averaged depends upon the horizontal tim e-base that allows you to log the acquired data to a more conventional
setting you have chosen. comma-separated values (CSV) file. I didn't investigate
The minimum and maximum values, calculated over that this feature deeply. It opens up in Excel and displays the
number of samples, are shown as red traces above and below accumulated values for all parameters over a 500ms interval.
the yellow trace. If you were to zoom out to the extent that You can change the 500ms period to some other value in the
each horizontal screen pixel represented one sample, these Preferences menu using the "reduction_frequency" setting.
red bounds traces will disappear. The Joulescope UI is quite customizable. If you select
Along the right-hand side of the waveform display is a Preferences from the File menu, you'll see the window displayed
window which shows the voltage and current values, as well in Figure?. One example of the possible custom izations is the
as the min, max, peak-to-peak values, and the standard starting_profile. You can change it from the factory default of
deviation. These are calculated over the period of time previous to app_defaults, Multimeter or Oscilloscope. You can
displayed in the waveform window. It also shows the elapsed enable automatic checking for updates as well as their source
time displayed in the waveform window, as well as the total (stable, alpha, beta). There are many possible customizations
charge during that elapsed time, expressed in coulombs. from this menu.
Whether collecting data or not, you can click on "Add Single"
or "Add Dual" to add marker(s) on the waveform display. TESTING THE JS220 USING THE EVK BOARD
As you move a marker with the mouse, the group of values While not included with a JS220 purchase, Jetperch also
mentioned in the last paragraph will be displayed for the point sells the small EVK Evaluation Kit 1 board for $99. This can
in time represented by that marker. You can place many single be used for routine tests of the JS220's performance. Tests
markers, and if you place a dual marker, it will include values done with the EVK would not duplicate the param etric testing
related to the time frame enclosed by those markers. done by Jetperch on each JS220 before leaving the factory.
The Waveform Control toolbar also has group of buttons However, they can be comprehensive enough to satisfy the
labeled "Signals." In addition to the voltage and current
waveforms, you can display a calculated power waveform.
If you have connected either or both of the inO, in i digital
input pins (on the back panel of the JS220) to some external
logic-level signal (target MCU GPIO pins, for example), you
can add a "mini logic analyzer" display by clicking on the
inO/inl buttons. This will allow you to relate the voltage and
current readouts to some real-tim e event. For example, you
could have your target MCU set a GPIO pin high at the start
of an ISR and drop it low at the end. Then connect that GPIO
signal to inO on the Joulescope. You could then relate the
voltage and current waveforms to the inO waveform displayed
on the JS220 UI, and observe the MCU's current consumption
while it was executing that ISR.
In the control toolbar, to the right of the Start/Stop
icon, is a round red icon that starts and stops the logging
of the acquired current and voltage to a disk file with a JLS
extension. When you click on one of these JLS files, it brings
up what looks to be a screen capture of the Joulescope UI
program, taken at the time that you triggered the capture.
This is what my Siglent SDS1202X oscilloscope provides when FIGURE 7
I "Prin t" the scope's display screen to a USB flash drive. This is the JS220 UI program's Preference menu, at the top of the oscilloscope
But wait—there is more magic going on here. If you look hierarchy. The UI program's startup configuration and defaults can be highly
at the properties of a JLS file, you can see that it is tagged to customized from this menu.
CIRCUIT CELLAR • APRIL 2023 #393
user of the unit's health if, for instance, something goes astray a PIO block, and given that the RP2040 is crystal-clocked, the
on the device under test (DUT) and there was a chance that waveform tim ing is extrem ely accurate.
the JS220's input lim it specifications were exceeded. Figure 4 The RP2040 MCU mounted on the EVK comes with
shows the front side of the EVK PC board—only four banana MicroPython pre-installed. Along with the MicroPython run
plugs are present on the back side. These plug directly into time interpreter, a Python program is also installed which
the voltage and current jacks on the JS220. runs a demo program that provides the voltage and current
It was tempting to get distracted by this board when I waveforms shown in Figure 6. This demo was not written for
started reviewing the JS220, because it contained an RP2040 any specific calibration purpose, but just to show that the EVK/
Pico MCU, which I am interested in. I quickly found out that Joulescope combination is working. However, MicroPython
the RP2040 runs MicroPython and can be re-program med to is running on the RP2040, and it provides a "shell" that is
perform specific tests that the user might want to run. accessed via a serial console. This is part of what is referred
The EVK board contains a USB-C socket and, like the to in Python as the read-eval-print loop (REPL).
JS220, comes with a USB-C to USB-A cable, so it readily While any serial terminal program on your PC can access
plugs into a standard PC's USB port. The EVK uses a USB-C RP2040's Python shell, the best method is to install the Thonny
socket only because USB-C is becoming common nowadays. application on your PC. Thonny is a basic Python editor featuring
The board itself doesn't take advantage of the power delivery Python-context autocomplete. It also contains a serial terminal—
(PD) features of USB-C. That is, it runs only on the 5V 500mA this runs in a window at the bottom of the Thonny screen. At
power that is available from a USB-A socket on a PC. startup, Thonny will ask you what hardware platform you are
The EVK also contains two programmable regulators with using. When you select the Raspberry Pi Pico, Thonny will know
outputs of 3.3V, 1.8V, 1.0V and 0.6V. One of the regulators is a enough to scan the available USB virtual COM devices and select
switching, buck regulator which can increase the 500mA available the EVK board automatically, as long as it's plugged in. This shell
from the USB-A port up to 1.0A, on the lower voltage ranges. console window will display "MicroPython (Raspberry Pi Pico)"
In addition to the programmable voltage sources is a and its COM port number at the bottom right. If you haven't
programmable current sink. This consists of a bank of eight configured it properly, clicking on this entry will bring up a
decade-related resistors which are program m atically switched menu, allowing you to select the Raspberry Pi Pico.
in, by transistors, under the control of the RP2040 MCU. From the shell, you can run or stop the demo program, as
These resistors range from IQ to 10MQ. Knowing the selected well as execute some functions which are a part of the demo.
power source (0.6V-3.3 V), you can determine the current So, even if you don't write your own MicroPython scripts, you
being passed through the Joulescope's Current+ and Current can do some useful EVK functions right from the shell itself.
term inals, and on through these resistors to ground. This All of this is clearly explained in the Github repository for the
circuitry basically acts like an exponential current sink DAC. JS220 Evaluation Kit 1 [2].
There are also two capacitors that can be program m atically Since MicroPython is an interpreted language, its run-time
switched in parallel with the resistors: lOpF and IpF. I haven't package and the REPL functionality have already been flashed
yet determined what these capacitors are for. to the RP2040. For your own programs, you must additionally
There is a 5-pin header on the board that provides access provide:
to the RP2040's GPIO010, GPIO011, GPIO012. These can
be programmed by the RP2040 as inputs or outputs, and • a Python script file that contains the program you want
can be used to synchronize other external devices, like an the RP2040 to run.
oscilloscope, to the program that is running on the RP2040. • a boot.py file containing boot-up instructions that specify
The Raspberry Pi Foundation's RP2040 MCU is a dual what Python script file to run, and that define some
core ARM Cortex M0. On the EVK, the RP2040 uses a crystal dependencies.
clock, so the MCU's timing is highly accurate. The RP2040 • optionally, some additional .py files containing library code
contains two programmable IO blocks, each containing four that is used in your main program.
state machines. The current waveforms are generated using
When an MCU has MicroPython flashed on it, there will also
be code that implements a file system using the MCU's Flash
memory. I'm more accustomed to Adafruit's CircuitPython,
R dspbury Pi ^tco where this filesystem shows up as a USB flash drive on your
N a rc Sac (bytes) PC when an MCU containing CircuitPython is plugged into the
boot.py 754
£
USB port. With MicroPython, in Thonny when you click on File
21618
** r gbJed_conUcller.Pi' 9766 -> Open, you have the choice to display the files on either your
rp2040 py 3673 local hard drive or on the Raspberry Pi Pico board itself. If you
tnrT_..py 0
select the latter, you'll see the files in Figure 8 as present on
the EVK board's RP2040. Opening the boot.py file, you can see
a few lines defining code dependencies, a statement defining
an instance of the class "Js220Evkl" (defined inthefileevk.py),
and statements that send out an information splash screen to
File name Cancel
the serial console and then run the demo program itself. The
demo program is run by invoking the "demo" function in the
FIGURE 8
evk.py file. If you understand the Python language, you can
The RP2040 mounted on the EVK board is loaded with MicroPython and the EVK
demo program (in Python). Using Thonny, you can examine the various files that
make changes to the evk.py file to run whatever EVK routines
are loaded in the RP2040's flash memory and which constitute the demo program. you wish. In Thonny, as you open various files, each will open
Best Test £ Measurement Products
From J r ^ u m p u E ELEcrronics
www, saelig. com Difference?
I —
^ ! a e li 9oom/u
a |u e a h t m
in its own tab, so it's easy to refer to library functions and specified voltage/resistance combination would indicate.
so forth as you go about the program development process. Indeed, I found that to be the case. The current using the 10Q
I applaud Jetperch's choice of the RP2040 MCU with sink resistor measured about 5% low, and the higher value
MicroPython as an effective way to run the EVKs, as well resistors measured <2.5% low.
as how they made it easy to re-program . Since the EVK To get at least some sense of the Joulescope's calibration,
S
can be easily programmed to emulate different "re a l-life " I decided to rig up a simple test circuit using several different
E measurement scenarios, it's well worth its $99 selling price. batteries. I chose batteries as the voltage source because
R
U they are completely free of any ripple, and they are completely
T
A
E
F HANDS-ON TESTING isolated from mains ground. I placed various resistor values
While I was working in the Chemistry Department at in series with the battery and sent the current through both
Dalhousie University, I had access to Keithley electrometers the JS220 and one of my m ultim eters. For currents <600pA
and an HP (now Keysight) 3458A 8.5-digit Multimeter. I could I used my Agilent U1232A Multimeter, as it has a 600pA
have done some meaningful tests on the JS220's calibration scale. For the few readings above 600pA I used the HP 3468A
with those instruments. Now retired, my test equipment Multim eter on its sole DC current range of 1A.
bench is not so well-endowed. For current measurements, I Figure 9 shows the results of those tests. As you can see, the
can use an HP 3468A Multim eter (single 1A DC range, 6-digit) Joulescope readings matched those of my two multimeters, at
or my Agilent U1232A Multim eter (10A and 600pA ranges). least to the extent of the numeric place values the multimeters
Since Jetperch had also sent me the EVK Evaluation Kit 1 displayed. While I don't have test equipment to match that used
board, it was easy to use that to check out the Joulescope over at Jetperch's facility, it was satisfying to see that the Joulescope's
most of its current ranges. Using the EVK is good for checking readings matched those of my meters. In all the current readings
out the overall health of the JS220, but it's not designed to be that I took, whether EVK-produced or from my battery-resistor
accurate enough to verify its calibration. circuit, the JS220's computed average values were always quite
However, as a quick test, I set the EVK to put out a voltage of steady and matched the values obtained from my multimeters.
1.0V by using the following commands from the shell window The JS220 comes with a nice set of jum per leads term inated
of Thonny (the " » > " is the MicroPython shell prompt): in a 2x5 pin plug which mates w ith the GPIO socket on the back
panel of the Joulescope case. When running the Joulescope
» > e v k .o ff() UI, the View menu will allow you to choose to display the GPIO
»>evk. power_l do (1.0) control panel (termed "W idget" in the manual) at the bottom of
the Joulescope UI screen. From the Waveform Control toolbar,
Use the following command to activate the current sink resistors: you can select which of the GPIO input pins (IN0, IN I) you
wish to have displayed. And, from the GPIO Widget, you can
»>evk.resistance = 1000 toggle the levels of GPIOs OUTO and OUT1.1 connected IN0 to
OUTO and IN I to OUT1, and proved that all four of these GPIO
Here you can specify resistors between 10Q and 10MQ, in pins were working correctly. In2, In3 and the BNC Trigger are
decade steps. This gives currents of 100mA down to lOOnA not implemented in the current Joulescope UI program. But
respectively. For finer control of the resistance values, you they can be used when you control the instrum ent with your
can combine the EVK's decade-related resistors by combining own Python scripts, via the pyjoulescope_driver).
them, as follows: While the JS220 User's Guide says that you can enable
or disable these two inputs using the IN0, IN I check boxes,
»> evk.stopO the current version of the Joulescope UI only supports this
»>evk. resistance_on(1000) feature on the older JS110 models.
»>evk.resistance on(100) The GPIO widget contains a drop-down list box labeled
"Voltage" that is described in the User's Guide. Here again, the
In all cases, the resistors are switched in using NPN description in the User's Guide reflects how the earlier JS110
transistors of an unspecified type. The VCE of these transistors works, and is different for the JS220. Currently, the Joulescope
will not be zero volts, so you would expect the currents that UI sets the JS220's logic level to an internal 3.3V power supply.
the Joulescope measures to be a bit lower than what the I confirmed this in my tests—the OUT lines produced 3.3V logic
levels and the IN lines switched at 3.3V/2 (CMOS switching levels).
4 A B C _________ P I asked Jetperch how one would set the logic levels using the VREF
1 Joulescope U1232A HP3468A Circuit pin and an external voltage source. This was their response: "The
2
3 ? 2484uA .25 uA
actual reference node is VREF through lOkfi and 3.3V through
3.2V & 12 Meg
267kQ resistor and optocoupler. So, even with the 3.3V reference,
4 3.193uA 3.19 uA 3.2V & IM eg
5 ] 30.978 uA 30.97 uA you can easily drive a desired voltage at the cost of a little current."
3.2V & lOOk
6 244.179 ua 244.3 uA 3.2V & 10k
7 3.131mA 3.13 mA 3.2V & Ik
A REAL-WORLD TEST USING AN ESP32
8 40.92 mA 40.89 mA 3.2V & 75 ohms
DEVELOPMENT BOARD
For my purposes, the JS220 would be most useful
9 555.7 mA 555.7 mA 3.5V & 5 ohms
10 238.8 mA 238.8 mA 1.5V & 5 ohm
perform ing measurements on my various projects that
involve battery operation and a project board which generally
contains an MCU with Wi-Fi or Bluetooth capability. The current
FIGURE 9
This is an excel spreadsheet showing the readings I obtained with the JS220 as well
consumption of the different members of the ESP32 family,
as by using a combination of my two multimeters. in the various operating modes, is fa irly well-documented.
circuitcellar.com
However, I use various ESP32 development boards in projects, to monitor a device's power consumption. It's easy to use and
and the deep sleep current consumption is often dominated its m ultim eter and oscilloscope modes cover most use cases.
by other circuitry on the development board itself and can't The data can be logged, in what I would call a processed
be easily determined without a measurement. basis, as a CVS file that an Excel spreadsheet can read. In
Most MCU development boards contain a USB port for Figure 12, each entry is the integration of the current or
power and flash programming or serial debugging. In addition power over a 500ms interval, by default. This interval can be
to the JS220 and the EVK kit, I also received a variety of changed in the Preferences menu if you navigate to the Device
custom front panels, one of which can adapt the Joulescope -> Settings -> reduction_frequency entry.
to measure USB current and voltage (Figure 10). These can The raw data is collected at a sample rate of 2 million
be purchased from Jetperch. samples/sec. by default. The round red icon in the Control
I wanted to try out the JS220 USB front panel, so I taskbar starts and stops the logging of this data to a file
connected up a DFRobot DFR0487 ESP32 FireBeetle board to on your PC. As I mentioned in the UI software section, this
the JS220 and used my PC's USB port for power. I had loaded a results in large files, and Jetperch uses a custom file form at
program into the ESP32 which would put the ESP32 into a deep (JLS file extension) to make visualizing this data easier.
sleep mode a few seconds after boot-up. The current readings However, the JS220 could just as easily be used as part of
that I obtained were much higher than the 15pA deep sleep an automated test equipment (ATE) setup. Its small size, and
current that DFRobot claims for this board. However, looking the wide dynamic range of its current readings, make it a
at the schematic, I recalled that the CH340 USB bridge chip good candidate for ATE. Because it connects to a PC via USB,
is powered up when the board is powered via the USB port there would be obvious lim itations on how many JS220s you
(but isn't when powered via the LiPo battery socket). You can't could use simultaneously, since PC computers have a limited
measure ESP32 deep sleep current this way, so I switched the number of USB ports. Even if you decided to add several USB
Joulescope front panel back to the original banana jack version. hubs to the PC, the JS220 stream s data at 8MB/sec., which
I then powered the DFR0478 via its battery socket using three would overwhelm the PC's OS if a number of JS220s were
AA cells in series (4.8V). I hooked the JS220's current terminals connected. However, if you plan to use multiple JS220s in the
in series with the positive battery lead (high-side monitoring). Multimeter mode, the USB bandwidth is a lot less than 8MB/
Figure 11 is a screen capture of my results. At the start are sec. The Oscilloscope mode already supports down-sampling,
several seconds in which the ESP32 is actively executing program but the down-sampling is currently performed on the host.
code. During this period the ESP32 is sending out serial data via Jetperch plans to move the down-sampling to the instrument
the USB port, which may explain the spikes seen in that interval to allow you to reduce this bandwidth as well.
(although it could be the RF modem in the ESP32 running in the Assuming you only need a reasonable number of JS220s
background, even though I did not call for any Wi-Fi activity). for a given ATE setup, how do you go about controlling
From the six-second m ark on, the ESP32 is in deep sleep and collecting data from them in an automated way? Even
mode. I added a marker in this region and the results were seasoned program m ers writing code for PCs are unlikely to
9.98pA (average). This was somewhat better than the DFRobot have much experience writing USB drivers that can handle a
specifications for the board, but this depends mainly on the data stream coming in at 8MB/sec. Windows and OSX are not
ESP32 itself, and could vary from device to device.
For comparison's sake, I disconnected the Joulescope and
hooked up my Agilent U1232A Multimeter, on the pA scale, in series
with the positive battery lead. Since the U1232A has a high burden
voltage on its 600pA range, I had to temporarily add a jumper
wire across the meter leads so that enough current could flow to
allow the ESP32 to boot up and execute for the six seconds before
deep sleep started. The Multimeter read lO.OpA during deep sleep,
which is right in line with the readings I got from the JS220. USB- Front Panel
A word to the wise: The first time I took the above
readings on the Joulescope, I had chosen a current range
of 180mA—the next highest range from what I expected the
ESP32's current consumption to be—during normal execution.
For some reason, I thought that the JS220 would auto-range
downward as soon as the deep sleep started. It turns out that
it doesn't, and the currents I saw during deep sleep were all BNC Front-Panel
over the place. This happens because the JS220 measures
across a 0.11Q shunt resistor on this range, and is using just
a small fraction of the 16-bit ADC's resolution (because the
voltage drop is so low with only microamps flowing). To get
accurate measurements over a wide dynamic range, you
must select "auto" for the current range. Lesson learned.
Banana Jack Front Panel
WRITING YOUR OWN JOULESCOPE
FIGURE 10
COMPUTER INTERFACE SOFTWARE These are the three optional front panels available for the JS220. They can be
For a hardware or software developer using the Joulescope swapped in for the banana jack front panel that comes standard with the JS220.
on the bench, the Joulescope UI program is perfectly sufficient The swap can be made in about one minute, by removing two screws.
CIRCUIT CELLAR • APRIL 2023 #393
true real-tim e operating systems, so latency equipment into a system control and data
issues could result in data being dropped. acquisition setup (SCADA). The LabVIEW
In academia and industry, LabVIEW by software is supported by drivers for most
National Instruments is a popular way to commonly available test equipment. I won't
integrate many different models of test offer my opinion on the pros and cons of
LabVIEW, other than to say that Jetperch has
chosen another way to allow users to integrate
the JS220 instrument into their own custom
test rig. How did they go about doing this?
To start with, the Joulescope UI program
is written in Python, and its source code is
available on GitHub [3]. While I am much more
comfortable with the C language, I acknowledge
that Python has become the programming
language of choice for many applications where
C used to dominate. If you are intending to write
a completely customized user interface program
for your SCADA setup, you could certainly peruse
the source code of the Joulescope UI and use it
as a template, of sorts.
When you download and install the standard
Joulescope UI on a Windows PC, you will end up
with an EXE file after the installation completes.
This EXE program runs without any external
Python framework being present. However, if
you want to customize the source code of the
Joulescope UI (obtained from GitHub [3]), you
must install Python 3.8 or later. Even if you never
do any Python programming, it's quite likely
that your PC will already have Python installed,
as it's used by other software. However, on my
FIGURE 11
PC, only Python 3.7 was installed (likely by the
This is a screen capture of a measurement taken on a DFRobot DFR0478 ESP32 board. The green marker ESP32 toolchain). Instructions on how to work
that I placed shows that the ESP32's deep sleep current is 9.98pA. This figure matches that obtained with the Joulescope UI source code, running
using my Agilent U1232A Multimeter and tracks with DFRobot's published specification for that board. under Python, can be found on GitHub [3].
Jetperch also supplies a Joulescope driver
A B C ___D E F which can be imported into your own Python
1 #time current voltage power charge energy program. The small snippet of Python code
2 0 0.01908 0.99516 0.01898 0 0 shown in Listing 1 can be run from Python, and
will collect 100ms of current and voltage data
3 0.5 0.00388 0.99481 0.00386 0.00194 0.00193
and print it out. As evident in Listing 1, Python
4 1 0.00799 0.99511 0.00795 0.00594 0.00591 is a high-level programming language and uses
5 1.5 0.00396 0.99505 0.00394 0.00791 0.00787 libraries to do all of the heavy lifting.
6 2 0.00037 0.99527 0.00037 0.0081 0.00806 In the Joulescope folder of the pyjoulescope
Github repository, you can find many Python
2.5 3.64E-O5 0.99544 3.62E-05 0.00812 0.00808
scripts which perform various tasks, such
8 3 2.59E-06 0.99553 2.57E-06 0.00812 0.00808 as writing the data out to a JLS file, and so
3.5 -8.41E-07 0.99562 -8.42E-07 0.00812 0.00808 forth. I didn't find much in the way of Python
10 4 0.01416 0.99544 0.01409 0.0152 0.01513 examples in the Jetperch/Joulescope examples
folder within the pyjoulescope_examples Github
11 4.5 0.0088 0.99471 0.00875 0.0196 0.0195
repository [4]—only one plotting routine that
12 5 0.00562 0.99514 0.0056 0.02241 0.0223 had no direct interaction with the Joulescope
FIGURE 12 instrument itself.
This is the CSV-formatted data, logged to a file, using the red circular icon in the control taskbar of the However, in the bin folder are 26 Python
Joulescope UI program. The data file easily imports into Excel. script files that perform most or all of the
functions you would need to use the Joulescope
instrument with your custom program. For
ABOUT THE AUTHOR
those scripts that take arguments, you can get
Brian M illier runs C om puter In te rfa ce C onsultants. He was an a description of the argument list, as in the
instrumentation engineer in the Department of Chemistry at Dalhousie following example:
University (Halifax, NS, Canada) for 30 years.
python3 bin\downsample_logging.py -help
circuitcellar.com 13
EMBED RELIABILITY
Rugged, Reliable Embedded Computing Solutions
WINSYSTEMS understands the risk and challenges of
bringing new products to market. We help technology
decision makers select the optimal embedded computing
solutions to reliably enable their products, giving them
more time to focus on product feature design and achieve
faster times to market.
By FIGURE 1
The SS-300 tube amplifier's
Avian Marinakis enclosure was designed to resemble
a 1960s Fender amp.
W
growing in popularity, there from a mobile application. By applying these
is strong interest in today's features to a lightweight package, the SS-
market for vintage tones 300 becomes a versatile, portable, all-in-one
with modern conveniences. However,
workhorse
with theamplifier. Now, let's dig into our
increasing cost of components, replicating development process!
a vintage amplifier for a reasonable price is
becoming less feasible. Also, most vintage VALVE (TUBE) AMPLIFICATION VS.
amplifiers lack the compatibility to be SOLID-STATE AMPLIFICATION
conveniently set up with modern venues and A priority in developing the SS-300 design
recording systems. was to cut costs, so you might be wondering
Working musicians seek superior music why we chose to use valve amplification,
equipment to represent themselves, and instead of the less-expensive solid-state
when considering an amplifier, a tube amp amplification. Solid-state amplification relies
is a superior choice. These amplifiers are on semiconductor components, such as
very expensive, however, and if the amp was transistors, diodes, and ICs, which are easier to
manufactured in the 1960s, it is even more obtain than the rare and expensive thermionic
expensive and desirable. vacuum tube. However, when you compare the
Our team at Sinusoidal Sound set out to output of the two types of amplifiers, there
develop a solution that offers the timbre of a is nothing better than the warm sound of the
vintage tube amp with a reduction in weight, valve amplifier.
cost, and size, that also provides compatibility To understand why, we must consider music
with modern venues and recording systems. theory—specifically, harmonics. A harmonic is a
We call our solution the SS-300. sound wave that is a multiple of a fundamental
The SS-300 is a 5W valve amplifier that tone. For example, the middle C of a piano
features everything a working musician needs: has a frequency of 256Hz. In this example we
an IR cabinet simulator, a multi-effects loop, will consider 256Hz as the fundamental tone.
and a mobile user interface (UI). It offers the When 256Hz is multiplied by two, the resulting
package of a tube amplifier (Figure 1) that frequency—called the "second harmonic" (and
visually and sonically resembles the design of a an "even harmonic")— is an octave of middle
1960s Fender amplifier, and provides a hybrid C. If you continue to double the frequency,
system that gives the user the ability to control the results are also octaves of C. It might not
circuitcellar.com
surprise you that multiplying 256Hz by three produces an "odd notes of the second harmonic and its doubles. A valve amplifier
harmonic"—in this case a G note, C's third harmonic. In general, produces even harmonics when overdriven, whereas a transistor
third harmonics produce a note one octave and one fifth higher amplifier produces odd harmonics when overdriven. This means
than the original. If we continue to triple C's frequency, we create the transistor amplifier will create a subtle tonal dissonance.
the sequence of notes G, B, D and F#. F# is not in the C major Valve amplifiers avoid this by introducing even harmonics, and
scale, and will not sound as pleasant when compared to C octave will instead add a fullness to the timbre of the instrument.
Plate Plate
current current
In in
Milliamperes Milliamperes
FIGURE 3
Graphs depicting how we biased the two gain stages of the 12AX7 pre-amp vacuum tube
16 CIRCUIT CELLAR • APRIL 2023 #393
FIGURE 7
Graphical DSP signal flow development system, used to design the firmware for the SS-300's effects loop, speaker simulation, and 10-band EQ
CIRCUIT CELLAR • APRIL 2023 #393
Wondom I store.sure-electronics.com
circuitcellar.com
effects, 10-band EQ, and IR selection. For the "12-inch answer we found was that PCBs are difficult to repair and
speaker in a messy living room" simulation, the simulation modify.
must be selected within the IR selection tab. This will execute To resolve this issue, we created three PCBs—an input
a block of code that sends the string "FIR_select_OOO" from board, an amplification board, and an output board. The
the mobile app to the ESP32. The ESP32 receives and parses reasoning behind this was that the input and output
the string, and then determines that you want to select the components are the most susceptible to damage, since
12" speaker impulse response. It then writes the related those components experience the most user abuse (such
FIR coefficients to the ADAU1701's memory, using the I2 C as inserting V4" jacks, turning potentiometer knobs,
protocol. The coefficients are accessed by the firmware, and flicking switches). For example, let's say the input
using the FIR filter signal block, and the FIR filter is applied board were to fail from excessive turning of the volume
to the output of the SS-300. Wow! it sounds just like it did knob because the user wanted to get it to 11. Instead of
on that fine day in the messy living room. replacing the whole PCB, only the input board would need
to be replaced. This provides a cost-effective solution. If a
POWER SUPPLY user wants to modify the input PCB so that the volume knob
Why did we call our amp the SS-300? "SS" stands for can go to 11, that can be achieved by dismounting the input
"Sinusoidal Sound," and "300" represents the backbone of PCB for an easy modification.
it all—a 300V, 250W switched-mode power supply (SMPS) We used Altium Designer to automate the design of
that provides +300V, +12.6V, and +6.3V to energize all the our PCBs. The three PCBs are double-sided, with top and
SS-300's features. We chose this power supply because it is bottom polygon ground pours. The priority of our PCB
lightweight, inexpensive, compact, versatile, and efficient. design was to minimize noise. We did this by using isolation
But why an SMPS, instead of the traditional linear ground vias around noisy traces with digital conditioning.
power supply? For all the righteous audiophiles reading this Filament supply traces were kept separate from any audio
article, before you get upset with our decision to use an signal traces, and all routes that crossed over were at a
SMPS for a tube amplifier, please hear us out. Traditionally, 90-degree angle to avoid crosstalk. When we tested our
tube amplifiers have been powered by linear power supplies PCBs for excessive noise and crosstalk, we were pleased to
for low noise production. They were the best choice when discover success in our design.
these amps were designed for guitar amplification in the By using PCBs instead of hand wiring, we eliminated
1940s. While most tube amps today still abide by the linear wires, which tidied up the SS-300 circuit. A clean circuit
power supply, we decided to experiment with the taboo. allowed us to place the DSP board and SMPS strategically
In the SS-300's initial design phase, we considered using away from the audio signal path to minimize noise. The
a linear power supply. In fact, our first design included a PCB design allowed us to assemble the SS-300 components
large and heavy power transformer and a 5Y3 tube rectifier. conveniently into the compact enclosure (Figure 1), and to
However, these two components were not only expensive provide the user with an easy-to-fix, lightweight package
but also extremely hard to source. We determined that that sounds amazing.
using an SMPS, thus eliminating these pesky and costly
components, would allow us to reduce the SS-300's weight, CONCLUSION
cost, and size, and provide suitable power for an MCU. Within our capstone's 14-week timeline, we were
These benefits come with the risk that a switching able to complete the SS-300. With this low-noise tube
power supply will introduce unwanted noise to the system. amplifier, working musicians can practice and record their
With this risk in mind, we added a 60mH choke inductor instruments at home, and produce the sound of a $2,000
to serve as a low-pass filter to eliminate any unwanted Fender Champ amplifier from the 1960s. They can replicate
high frequencies that the SMPS could generate. Thankfully, their favorite speaker cabinets, and apply their favorite
our amp produces very little hiss and noise, and when we dynamic effects by using the mobile UI. Finally, they can
compared it to a similar amplifier that uses a linear power give their backs a break by leaving their speaker cabinets,
supply, the SS-300 was superior, though we were unable effects boards, and heavy tube amplifiers at home. With the
to record enough data for noise comparison calculations. SS-300, the musician can arrive at the gig with the SS-300
Admittedly, we left this part of our design in the hands of in one hand, and a nice cold beverage in the other, and sit
the SMPS manufacturer, and we were pleased with the low- back while the rest of the band struggles to load their heavy
noise results. gear onto the stage.
The SS-300 design process served as an excellent
PRINTED CIRCUIT BOARDS introduction for our team to learn about professional audio
If any audiophiles have made it this far, hopefully you'll equipment, and provided a great foundation on which we
stick around after you learn that our tube amp is not hand- can improve. Given more time and resources, we would have
wired. Part of our capstone requirements was to design allocated more memory by upgrading the ADAU1701 chip to
and manufacture a printed circuit board, so the SS-300 is the ADAU1787, to allow for more dynamic effects, and more
indeed on a PCB. FIR coefficients to improve the quality of the speaker
Those of you who are not audiophiles are probably simulations. Introducing cross-platform compatibility for
wondering what's the big deal about using a PCB for a tube our application would improve the user experience. Sound
amp. According to the tube amp enthusiasts found deep tests by swapping and calculating values for tone shaping
in the Internet forums, PCBs are frowned upon, and are components would have improved the sonic quality of the
inferior to a hand-wired circuit. When we asked why this amp. However, we are pleased with what we're able to
is, we received subjective opinions; the only reasonable achieve within the window of time given.
20 CIRCUIT CELLAR • APRIL 2023 #393
rduino boards and Arduino-based developers to develop their tasks. Aside from
projects are becoming more and more its size (small enough to run on an MCU), it has
popular. Arduino is so well known and one major difference when compared to a GPOS
well documented that it has become (general purpose operating system), such as Linux,
synonymous with "embedded system" for those Windows, Android, and other multi-user operating
who are starting to learn how to design embedded systems. It prioritizes the tasks' time-to-execute/
systems. It isn't an exaggeration to say all response time window (that's where the "Real-
beginners in the embedded systems world either Time" prefix comes from) over executing many
started their journey with an Arduino board, or tasks as possible. This means that an RTOS ensures
used one at some point in their study process. that applications are executed in the desired (or
Given the relevance of Arduino-like projects expected) time window, and that their responses
in the embedded systems world, using a real are provided in the expected time window, too.
time operating system (RTOS) in it seems to be Therefore, an RTOS is a good choice of
a must-have feature, because of all the benefits, operating system for devices that rely on well
flexibility, and reliability it can bring to an defined response times, due to the critical nature
embedded software project. of the jobs they need to do. That's the main reason
This article focuses on RTOS, and shows those key-systems modules of aircraft, motor vehicles,
who aren't fam iliar with FreeRTOS how to use it heavy machinery, and other important machines
with an Arduino Mega board (Figure 1). This is use an RTOS as an embedded operating system
a good starting point for beginners who want to to orchestrate everything in terms of embedded
learn how to use FreeRTOS, by using a hands-on software.
approach with a project that has a display and a FreeRTOS is distributed under MIT's open-
push button. source license, and has been developed in
partnership with major global chip companies for
WHAT IS FREERTOS? more than 18 years. Also, FreeRTOS is currently
FreeRTOS is one of the most popular and supported by more than 40 microcontroller and
market-leading real-time operating systems microprocessor architectures, so it is an excellent
available today for microcontrollers and small choice for those who need an RTOS for embedded
microprocessors. It was created by Richard Barry software projects that run on either old or new
around 2003, and since then has become one of microcontrollers.
the most commonly used and reliable embedded Due to Arduino's growth in popularity over
operating system options available. the years, FreeRTOS has been introduced into
But, what's an RTOS? In short, an RTOS is an Arduino's world, and can be run in Arduino
operating system, which means it can manage boards. FreeRTOS is supported as a library for
computational resources and applications Arduino IDE [1][2], and it's working as a FreeRTOS
execution, serving as a reliable basis for official port for Arduino boards microcontrollers.
circuitcellar.com
This surely has contributed to FreeRTOS' growth in popularity It leads to an interesting advantage: using an operating system
in recent years, and also surely helped embedded systems that contains time slice technique will enhance the performance
enthusiasts to learn how to work with an RTOS in an embedded (compared to a serial execution of many tasks), since each time
software project. frame is used for a task to run—something that isn't always true
when executing functions in a series (that is, the next function
BASIC ELEMENTS OF FREERTOS executes only when the prior function finishes execution).
A Set of Tools and Concepts to Develop Safe and Reliable In operating-systems-based solutions, the applications (or
Software: FreeRTOS (and every RTOS available) has a set of tasks) sometimes need to communicate with each other to
tools and concepts to abstract and make it possible to use an exchange data required to run the jobs they are programmed
embedded operating system. This set of tools and concepts for. To better understand this, take, for example, a common
concerns how the developer can create an application to run in blender. Let's pretend this blender has embedded software
this operating system, how an application can safely interact that uses an RTOS as an operating system. When the power
with other applications running in the same operating system, button is pressed, the task that manages the buttons needs to
and how one application's execution can be prioritized over inform this action to the task that manages the electric motor
other applications. powering feature, so this motor is able to turn on or off.
An RTOS "Application" is a "Task": First things first. In This communication between different and isolated
RTOS, an "application" means a "task." It means a task is tasks is called "inter-process communication" (IPC). IPC is a
an abstraction of a dedicated software, a role played by an safe mechanism for exchanging data between two or more
application in a GPOS. Also, a task must be scheduled to be processes without data corruption, and ensuring the data will
executed by the FreeRTOS kernel. A schedule process informs reach all the tasks that need them.
the FreeRTOS kernel that a referred task must be executed, In FreeRTOS, the "queue" is a mechanism used for making
and its execution must be managed by the FreeRTOS kernel. IPC. A queue allows data to be inserted in and read out in an
A "task" is literally a portion of software (a function) ordered way. Then, a task inserts data into a certain queue,
containing its own code, features, variables, and so on, which and a task that needs this data tries to read the queue, and the
means a task can be seen as a module of an embedded software tasks that read this queue will get this data in the exact same
project. In FreeRTOS, each scheduled task receives a memory order in which it was inserted to the queue. In FreeRTOS, this
region (dynamically or statically allocated, depending on how order is the First In, First Out system (FIFO). In FreeRTOS, each
FreeRTOS was configured) to work, additional arguments queue has a memory region allocated for it, and each element
(optional), and a priority. of a queue has the same data type—integer, float, character,
A task is allowed only to directly manipulate the memory a data structure, and so on. So, be careful and wise when
region it has received in the schedule process. This contributes dimensioning queues, since oversizing queues isn't a good
more safety to the whole software solution, since a task cannot practice and can cause a microcontroller to run out of RAM.
accidentally read and/or write another task's memory regions. Sharing Resources Safely: The next FreeRTOS tool is related
Also, the FreeRTOS kernel decides which task will be to accessing shared resources in a safe way. Think about a
executed first (or which task will be executed in a certain GPIO that can be controlled (set or reset) by two or more tasks
time frame, when two or more tasks are eligible to run at running in FreeRTOS. Because tasks are running on a time slice
that referred time frame) based on task priority. This feature scheme, conflicts are likely. This means a task is using a shared
ensures that critical tasks are always prioritized over less resource and, right after the context changes, another task
important tasks. Priority is defined by the developer, so be tries to use the same resource, thus making two tasks compete
careful (and wise) when choosing the tasks prioritization of a for the shared resource. The result of this situation is crystal
FreeRTOS embedded software solution. clear—there will be a conflict in this shared resource, making
Another important thing regarding tasks is how they're the manipulation of this resource a mess.
executed by a CPU, keeping in mind that a CPU (a CPU core) For a bigger picture of how this can be very bad, let's
can only run one task at a time. To enhance performance and extrapolate to a more critical situation. Imagine an electronic-
make tasks run seemingly as if they're running in parallel controlled system where a GPIO is a shared resource, and this
(looking like all tasks are running at the same time), a GPIO is responsible for controlling an operation in a heavy
technique called "tim e slice" is used. Time slice is a technique machine, such as making a payload move up and down on
that makes a CPU execute (or resume) one task briefly (usually a crane. If this GPIO gets into a shared-resource conflict
some milliseconds), then pauses it and executes (or resumes) situation, the consequences could be catastrophic. Injuries
another task, then pauses it, and so on. Then the CPU can run or even death could happen to someone near this machine, if
a lot of tasks by using this resume-pause-change task cycle at payload manipulation got out of control.
an incredible speed. Each time a new task is prepared to be To solve this problem, FreeRTOS provides a resource named
executed in this cycle, we often say task context is changed, "Semaphore (MUTEX)." This resource controls the access to
since task context is a set of data, and each data set has to a shared resource, thereby prohibiting two or more tasks or
inform everything concerning its execution. routines from accessing this shared resource in a conflicting
Because the CPU can run fast (the more megahertz you way. Semaphores in FreeRTOS behave very much like traffic
use as CPU clock, the faster it runs), the observed result for semaphores (traffic lights) in real life for vehicles on the street.
us humans is that all tasks are being executed at the same The street is the shared resource, and to avoid conflicts due to
time. But what really happens is that the CPU is executing simultaneous shared resource usage (= cars crashing), the car
several tasks' fragments for a short amount of tim e—up to drivers need to check the semaphore before using the street.
thousands of tasks context changes per second, depending on In the FreeRTOS context, it means each task that needs
how FreeRTOS is configured. to access a shared resource must first check the resource's
CIRCUIT CELLAR • APRIL 2023 #393
referred semaphore to see if this shared resource is already operating system is being constantly developed, tested and
being used by another task or if it's available for use. Before a debugged, contributing even more to its reliability.
task takes control of the shared resource, the shared resource's Portability: I f you need to port software to another
semaphore needs to be taken (or locked), indicating to other microcontroller, this can be done much more easily when both
tasks that now the referred shared resource is busy and must microcontrollers are using the same operating system. Because
not be accessed at that time. the operating system is the same, your work as developer will
Task Prioritization: Considering that (pieces of) tasks are be pretty much to configure it to attend to your needs, and
executed quickly by a CPU (time slice), there will be time frames port the tasks to the new software. It is sim ilar to installing the
when FreeRTOS must decide which task must be executed first, same software in two PCs with the same operating system; the
when two or more tasks are eligible for execution at that time new application probably will work great on both PCs, since the
frame. FreeRTOS, itself, is ju st an operating system; it cannot operating system is the same.
guess which task executes first, since FreeRTOS isn't able to Code Reuse: In FreeRTOS and in some other real-time operating
interpret your code. systems, the task creation process allows parameters to be passed
The way FreeRTOS decides which task is executed at each into the function that implements the task. With that said, tasks
time frame in this situation is called "task prioritization." that should have similar operations can be written as only one task
Task prioritization is represented by a number, from 0 to an function code, and the parameters passed in task creation contain
upper lim it defined in FreeRTOS configurations. The greater information on specific features of these tasks and how they must
this number is, the more priority the task has. This number is behave. This is a valuable approach, because it encourages the
passed to a task on its schedule process. reuse of existing code implementations, thereby increasing overall
To understand how FreeRTOS decides which task should software quality, and makes tasks easy to maintain.
be executed on a certain time frame, let's suppose that two Safety: A sad but true fact about software is that it always
tasks, called A and B, are eligible to run on a certain time frame. has failures, so it is always vulnerable to security flaws. When
FreeRTOS decides which task execute first by doing the following: a security flaw in the operating system itself is found, and a fix
is available for it, almost 100% of tim e it only implies changes
• If Task A priority is greater than Task B priority: Task A runs in the operating system side, and your tasks and routines
in this time frame and Task B will be executed later. won't need to change at all. This is a great advantage, because
• If Task B priority is greater than Task A priority: Task B runs operating system fixes can be applied w ithout demanding time
in this time frame and Task A will be executed later. from you or a development team on fixes.
• If Task A priority is equal to Task B priority: Since tasks
priorities are the same, FreeRTOS executes both of them in PUTTING FREERTOS AND ARDUINO
a round-robin way; it switches between tasks (Task A, Task TOGETHER: INSTALLING LIBRARIES
B, Task A, and so on), executing them in the next needed The firs t step for using FreeRTOS with Arduino boards and
time frames. In this case, each amount of time a task Arduino IDEs is to install the FreeRTOS library into the Arduino
executes is called "quantum." IDE. From this point, it's assumed you already have the latest
Arduino IDE installed on your PC. I f not, please download it
Therefore, as indicated in the foregoing FreeRTOS tools and from the Arduino Download webpage, and install it before
concepts, be careful and wise when choosing task priorities. proceeding. The link to this page can be found on Circuit
This decision highly depends on the software solution, itself, Cellar's Article Materials and Resources webpage
and you must think carefully about which priority level you Next, download and install FreeRTOS Arduino library. The
give each task. link to the library is also available on Circuit Cellar's Article
Materials and Resources webpage. Download it into a folder
WHY MY EMBEDDED SOFTWARE SOLUTION you can easily find on your PC. Then, in the Arduino IDE, go
NEEDS AN OPERATING SYSTEM to "Sketch > Libraries > Add .zip library." A window will show
Using an operating system in an embedded software asking you to select the .zip file containing the library to be
solution may not always be easy; however it's crucial when added. Navigate to the folder you downloaded, and click on
you're trying to get a reliable, robust, safe, and easy-to- "Open." After this procedure, the Arduino FreeRTOS library is
maintain software solution for your project. Using a well- installed and ready to use in Arduino IDE.
developed and well-tested operating system ensures that the For the practical example/project included in this article,
basis for all your software is something you can trust. It also you'll also need the library for 16x2 alphanumeric I 2 C LCD display
allows you to focus on your application and task development, (Figure 2). To install it, download LiquidCrystal_I2C library from
and let the operating system take care of managing critical the its original Github repository [3]. Once you have downloaded
computational resources, such as CPU, memory, and I/Os. it, repeat the installation procedure shown for Arduino FreeRTOS
When you put a well-developed and well-tested operating library. After installing these two libraries, you're good to go.
system into your embedded system project, you'll automatically
get four key advantages to your whole embedded software COMMON FREERTOS APIS
solution, as described below: The most common FreeRTOS application programming
Reliability: The operating system provides microcontroller interfaces (APIs) are listed below. Full details on all
hardware access, memory management, Inter-Process FreeRTOS APIs can be accessed from FreeRTOS APIs official
Communication and a lot of other critical features. It will take documentation [4].
care of these provided resources reliably, making your life
easier as a developer. Also, it means bugs and malfunctions Main APIs for tasks Management:
related to operating systems tend to be minimal, since the x T a s k C re a te C ): Schedules a task. Its parameters contain
circuitcellar.com
start their projects using Arduino and FreeRTOS as a real-time • One LCM1602 IIC
embedded operating system. • One USB 2.0 cable type A/B (for programming and powering
Assuming you've already installed all needed libraries as the Arduino Mega board)
described earlier, the first step is to configure the Arduino • One 16x2 alphanumeric I 2 C LCD display (Figure 2), with any
Mega board as target hardware in the Arduino IDE. To do so, background and font color you like
in Arduino IDE, go to "Tools > Board > Arduino AVR Boards" • One push button
and select the "Arduino Mega" or "Arduino Mega 2560" option. • One 4.7kQ, 0.25W resistor
What Do I Need To Reproduce This Project?: To reproduce • One 400-point breadboard
the project described in this article, you'll need the following • Some male-female and male-male jumpers
components:
Figure 3 is the Fritzing diagram for the practical example,
• One Arduino Mega board (Figure 1) showing how the Arduino and other components are connected.
Listing 3
/* Tasks schedulling */ Code for tasks creation and
xTaskCreate( scheduling
task_lcd_displ ay /* Function which implements this task */
, “display” /* Task human-readable name (for debug reasons) */
, 156 /* Amount of memory allocated for this task (in words) */
, NULL /* Parameters passed to this task (in this case, none) */
, 5 /* Task priority */
, NULL ); /* Task handler, optional parameter (in this case, none) */
xTaskCreate(
task_push_button
, “button”
, 128
, NULL
, 6
, NULL );
delay_for_freertos(PUSH_BUTTON_DEBOUNCE_TIME);
push_button_state = PUSH_BUTTON_PRESSED;
push_button_state = PUSH_BUTTON_NOT_PRESSED;
Listing 4
Code for push-button task
CIRCUIT CELLAR • APRIL 2023 #393
v o id t a s k _ lc d _ d is p la y ( v o id *pvParam eters )
w h ile ( l)
1c d . s e t C u r s o r ( 0 , 0 ) ;
1c d . p r i n t ( “ P u s h -b u tto n :
1c d . s e t C u r s o r ( 0 ,1 5 );
1 c d . p r i n t ( “ Pressed 1 “ );
}
e ls e
1c d . s e t C u r s o r ( 0 , 0 ) ;
1c d . p r i n t ( “ P u s h -b u tto n : “ );
1c d . s e t C u r s o r ( 0 ,1 5 );
1c d . p r i n t ( “ Not p ressed “ );
1
LCR-Reader-MPA
AU-in-One Multimeter
C COMH □ * Figure 4
Serial monitor outputs
t ft** i * * s G ft tr r d when the push button is
t puM »-toattoa * t * t * ft** l * * n r*:*L**-d
t (iwi*n-t j i t s * ft** t* * n (> ♦ * * * * pressed and the push
i F u * a - t . t t e n ft** p * m p ******
t puab^toutiM i u i * ft** t**f* r t f t r n d
button state is received
i ota ft** b e ta p *« ** * 4 in the LCD display task
F
E
i p u a a -to u tio a * t * t * a** t* * n » * ;* i* * il A
t t ^ » f t » t * t * ft** t « t i* c * ; r * d T
U
R
E
S
t!Ut> M te iM * !
Finally, note that both tasks (Listings 4 and 5) make use of semaphores to
manage the serial debug interface, a resource shared between both tasks. This
approach ensures that only one task will be able to write debug messages to the
serial debug interface each time, without any chances of overlapping or spoiling
debug messages.
CONCLUSION
I hope I've adequately covered the main elements of FreeRTOS and how to use it
with Arduino, including the necessary libraries to do so. More importantly, I hope
now you'll be able to develop better and more robust embedded software projects
with FreeRTOS as a solid foundation. Until next time!
Figure 5
LCD display showing the last push-button state received by the LCD display task
A B O U T THE AUTHOR
E
R
U
T
A
E
F
H
C
E
T
GETTING IN TOUCH WITH YOUR SENSITIVE SIDE am also, as mentioned in my bio, an author, and some of my
Here we are again. Another month of our lives inscribed favorite genres to write in are science fiction and fantasy,
upon the immutable ledger of the past, and as I'm pretty sure especially short stories.
Dante' once said while contemplating his own existence, "It's "But what does all that have to do with sensors?" you
just one damned thing after another." Philosophy aside— it wonder. Ah! I am so glad you asked. Sit back, kick off your
occurred to me, dear reader, as I set my virtual pen upon shoes, grab an adult beverage (assuming there is one handy),
electronic paper, that this is the fourth Technology Feature and marvel as I tie all this drivel up into a neat package that
we've shared together! is totally relevant to this April's Tech Feature topic.
The digital ice has been broken, it's no longer our "first To wit, the genres of science fiction and fantasy are all
date," and the fact that you're still here reading implies a about strange worlds and the heroes who explore them.
certain level of commitment. We can get comfortable, let Often, sci-fi and fantasy heroes are superhuman beings who
our hair down, put our feet up on the couch, and be more can perceive the arcane and gather hidden information from
intimate. I can see you're getting a little antsy, but before their surroundings. The heroes in my stories also have funny
you cough, break eye contact, and quickly flip the page to a names and dark streaks of humor. The alien environments
less needy writer, I'm not suggesting we pick out curtains or that these superhumans find themselves in may be distant
anything! To me, being half Irish and an engineer, emotion is planets, mysterious dimensions, or impenetrable dungeons.
like kryptonite. All I want to do is share some friendly details, They could special powers or mutant abilities—super senses,
likes and dislikes, favorite authors—that sort of stuff. if you will.
For instance, you may have read in my bio that I am an We love sci-fi and fantasy stories because through them
"industry insider." I must admit that specific qualification we can live out our dreams. In the real world, where we lack
was news to me as well. However, I've been active in this Spidey senses or X-ray vision, we must invent devices that
field for over four decades, and I do know my way around provide these powers. Enter the sensor tech developers and
a lab. Physically, I'm of middling height, average build, and integrators (drumroll please) stage left.
somewhat follicle-ly challenged. I am both a father and a There you have it, topic managed. At this juncture indulge
grandfather, an above-average tennis player, and I like long me as I digress for a sentence or two and give a shout-out
walks on the beach at sunset... er, okay, now I'm going to to our publisher, KC. I do this because, unbeknownst to you,
back away slowly. all the topics for the Tech Feature were picked out by him,
In all seriousness, I do want to share some details, and I'm and then assigned to me to write up. I have full leeway to
going to tie them all up with this month's topic too. Speaking write whatever nonsense comes into my April-foolish head
of April, my birthday is on the first of that month, and I am about them. But as I do my homework, going down the list
a proud April fool. Besides being a card-carrying OG-EE I and researching each one, I've found interesting new facts
circuitcellar.com
that I would likely not have taken the time to TINKER, TAILOR, SENSOR, SPY...
learn if left to my own devices. Knowledge, Digression managed, on to our main
as they say, is its own reward, and I find that topic: sensors. Sensor technology, and the
I'm enjoying the educational experience that integration of same, is a field of incredible
comes along with writing these pieces. Rest breadth. This follows from the fact that
assured that as you continue to see these sensors are employed in every industry,
missives published month after month, at varying in form, application, and usage
least one of us is having a good time. depending on the need. My research leads me
Anyway—focus. We were talking about to believe that most people are familiar with
superpowers, and that is what sensor tech sensors that operate in the electromagnetic
is all about. As the late, great Sir Arthur spectrum, ranging from digital cameras
Clarke once said, "Any sufficiently advanced (visible light), remote controls (infrared, or
technology is indistinguishable from magic." IR), cell phones and radios (microwave, UHF,
And face it: we are the mages and wizards of and VHF), all the way down to DC. I would
our technological age. I'm sure I'm not alone categorize these sensors as super "eyes," if
when I say that most normal folks look upon you will. There is also another common class
what we do as pure sorcery—that is if they of sensors that mimic hearing, including
think about it at all. Members of our Ancient microphones, pressure sensors, ultrasound
Order know that everything we do is based on pick-ups, and the like. I was fascinated
physicsand mathematics. But to the layperson, to learn about sensors that mimic touch,
these terms are no more meaningful than providing feedback for advanced robotics
alchemy or thaumaturgy. Consequently, ours and prosthetics, and smell, using incredibly
is a singular profession, and we must accept sensitive detection devices for various
that a deep understanding of its nature is chemicals and environmental factors. "Taste"
beyond the ken of most. All that said, let me sensors have also been developed, allowing
roll up the sleeves on my star-speckled robe, rapid analysis of liquids and semi-solids for
place my wizard's cap on my hairless crown, process control. All these devices augment
and commence. our limited human sensory range, giving us
TABLE 1
Sensor Developer Roadblocks (Source: AgSensor Solutions)
CIRCUIT CELLAR • APRIL 2023 #393
noses as sensitive as that of a honeybee, or hearing keener specialize in. As you might imagine, some of the applications
than a bat's. Put that way, it sounds pretty superhero-ish eh? are of interest to the intelligence agencies of the United States
Well, it gets even wilder. government, and to law enforcement. These types of sensors
The companies who develop and manufacture these provide a key component in the security of our border,
devices are almost as diverse as the sensors themselves. enabling us to detect and interdict contraband such as illicit
Consequently, one of the main obstacles in creating and drugs, or thwart illegal activity such as human trafficking or
marketing sensor tech is not what to develop, but how to find a smuggling. Superhero stuff indeed.
sustainable niche for your products. There is a lot of cutthroat
competition in the space, and patenting and guarding your CHALLENGES: TO SENSE OR NOT TO SENSE
underlying intellectual property is key. One of the first companies I found in researching this
In the next few sections, I will present some of the article was AgSensor Solutions. It provides a good analysis
challenges that affect this industry, then give a few examples of the current state of the sensor technology market on
of relevant companies and the sensor technology that they its website [1]. It turns out that AgSensor is not a sensor
development company, but rather a consortium formed from
three partner companies: the product design and packaging
S E N S O R D IM E N S IO N S firm LogiSync, Tailgrass Technology Partners, which is a
consulting organization specializing in animal health, and AGD
Consulting, a veteran-owned strategic advisory firm servicing
the global agricultural technology, food, and investment
sectors.
This partnership is in the business of productizing sensor
technology. It provides the know-how and resources needed
to guide the developers of a novel or innovative sensor through
its productization, and to target the market niche(s) that will
be best served by that product. To that end, AgSensor could
be a valuable resource to readers of C irc u it C e lla r who have
val u e
created a unique sensor technology but lack the in-house
expertise to bring it to market.
FIGURE 1
Table 1 gives a comprehensive overview of the challenges
Effective Sensor Development (Source: AgSensor Solutions) in this process. As AgSensor Solutions states on its website,
many sensor developers have sound technology, great
engineering, and a unique approach. But to quote Hobbes,
their experience when bringing their offering to market is
"nasty, brutish, and short." Often, developers suffer from
what AgSensor refers to as the "porridge problem." Succinctly
CONDUCTIVITY APPLICATIONS
put, the sensor technology is either too hot, meaning that it
PRINTING attempts to do too much and ends up being narrow in its
Cur e*** ■ F w * Stfwacn
M m m w * I application as well as difficult to use and integrate, or too
L 4* D u rtP *
cold, meaning that the technology in question does too little,
offering limited value to downstream integrators.
As in the story of Goldilocks, AgSensor helps developers
M * A C d rtrt
■ GdaAtnartt LAjRtonrtj get their sensor tech packaged "just right," with a balance of
■ LMta Dwaranfi * Aferti
* L * * A toaartaca Ov*k *cr complexity and value-add that facilitates its acceptance in the
target market. Figure 1 depicts this multi-dimensional problem.
PLAHNC * METAL
TREATMENT
* A m e m * UtaHtom* A C w
SENSOR TECH: WE'RE GIVIN' HER ALL SHE'S
GOT CAP'N!
« LM * O M d m • A la m
S W M M H G POOLS
• B M M W fT D fi G « *M | Sensors—how would we continue our five-year mission
POWER PLAMTS
« a ttuwcfcwi T E IT X E S without them? I can tell you that sending out a bunch of
■ U n t t v C « *o f
- * Spa* aQo^ng k m 1 vague mission reports wouldn't make us any friends back at
• A rty M t M . O W TM L* C W W P rtO H
> LMA A AWW M a a w m a rt 1 Q trtr* Starfleet, that's for sure. If we weren't manning the sensors
W VR O M M C N T AL • A a m * Mkji in u n a
and gathering all that precious exoplanet data, they might
• L a * Dm k M h A A*w m
■ L a ** A Hartac* D M e *
f*M **
suspect that we were boldly going with too many Rigelian
• TUS1*v
* • ■ • * 1 Caotng M m v t a r t w girls, but I digress.
• C w *w r< WATER TREATMENT A
W m m m o t AC a rt P U M FC A nO W As I mentioned earlier, sensors are basically our super eyes,
• bbf*orwig ■ A frtR w f a M M *
* Lart DatactaDR A Atarm
• A Q r tft f
■ fMMn~lr.x~. | T [Jfi CcrtrrWI ears, nose, and hands. Properly used, they are the difference
■ ( * Gone ** a
• Rkwig
* MtrtMvtg A
between beaming up a six-pack of cold ones from the surface
TrMmari
of the ice moon Hoth, without accidentally bringing back half
■ M i * * * M onAbm g I
of a Tauntaun at the same time (to mix a couple of sci-fi
cannons). Some of the companies and academic institutions
FIGURE 2 that are developing the next generation of sensor tech are
Sensor applications (Source: Sensor Development, Inc.) explored below. I found most of them fascinating.
circuitcellar.com 31
A B O U T TH E A U TH O R
M ich ael Lynes is an entrepreneur who has founded several startup ventures. He was awarded 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, working on ancient cars, backyard birdw atching, and taking am ateur
photographs. He's also a prolific author with over thirty works in print. His latest series is the Cozy Crystal
Mysteries. Book one, M oonstones a n d M urder, is already in print, and book two is on its way. His latest
works include several collections of ghost stories, short works of general fiction, a collection called Angel
Stories, and another collection called Novem ber Tales, inspired by the fiction of Ray Bradbury. He currently lives w ith his w ife
Margaret in the beautiful, secluded hills of Sussex County, New Jersey. You can contact him via email at m ikelynes@ gm ail.com .
32 CIRCUIT CELLAR • APRIL 2023 #393
Resources
AGD Consulting | www.agdconsult.com LogiSync | www.logisync.com
Standoff
Threat Type Technology Applications Data Products
Range
Surface deposited Alarm to the presence
Sensitive site assessments, vehicle
chemicals (liquid, Proximity (0.5m Standoff UV Raman of a chemical or
mounted/unmounted reconnaissance,
solid) or explosive - 1.5m) Spectroscopy explosive threat, surface
check points, urban search.
residues contamination map.
TABLE 2
Active sensors (Source: S3)
34 CIRCUIT CELLAR • APRIL 2023 #393
Datasheet:
32-Bit Microcontrollers
he 32-bit microcontroller (MCU), that found in these chips. Almost every product
workhorse of embedded systems, featured this month sports a 32-bit Arm Cortex
has experienced continuous and CPU, whether an M0+, M4, M7, or M33. There are
steady innovation and growth in its a couple of exceptions to this rule, notably from
capabilities for decades by taking advantage tech giant Texas Instruments. But the domination
of the latest in semiconductor technology of Arm cores has become a predictable pattern
integration. Of course, a singular "it" doesn't in our annual 32-bit MCU Datasheet coverage
do the variety of 32-bit offerings on the market over the last few years; the industry is evidently
today any justice. smitten with them, for the time being.
Here, in this month's Datasheet gallery, All of the products featured in this month's
you will find devices designed for applications gallery were released since our last article
ranging from residential smart meters to covering these devices. As always, bear in mind
rugged, industrial environments. Between those that this collection represents only a small
poles, we have chips designed for general- sample of the overabundance of 32-bit MCU
purpose applications, affordability, developer available today. Even within individual
accessibility, IP and data security, power companies, it was difficult to choose which of the
efficiency, and, of course, diminutive size many new 32-bit MCUs should be given the
requirements. spotlight. My aim in their selection was to
If there's a common thread, it's the various attempt to give a glimpse of the sheer breadth of
incarnations of Arm Cortex processors to be functions that new 32-bit MCUs are serving.
circuitcellar.com 35
Ultra-Low-Power Chip for Best-in-Class Compute in a SoC Series Built for Smart
Complex Sensor Processing Rugged Design Metering Applications
Analog Devices' MAX32672 is a Infineon Technologies' XMC7000 M icrochip Technology recently D
reliable, highly-integrated, u ltra -lo w - series are designed for high-end debuted a new PIC32CXMT fa m ily of A
T
A
power 3 2 -b it m icro con tro ller (MCU) industrial solutions, bringing best-in-class 3 2 -b it MCUs geared s m a rt m etering S
H
th a t hails fro m Analog's DARWIN compute performance and low-power applications. Its PIC32CXMTSH series E
E
fam ily. Equipped w ith an Arm 40nm process technology. This new MCU offers up to class 0.2 m etrology accuracy T
Cortex-M4 processor w ith a flo a tin g fam ily (consisting of the XMC7100 and the over a dynam ic range o f 3000:1 w ith in
point u n it (FPU), 12-bit 1MSPS ADC, XMC7200) offer single and dual-core Arm an industrial tem p era tu re range. Built
and 1MB o f flash and 200KB of SRAM, Cortex-M7 cores, respectively, and they around dual Arm Cortex-M4F RISC
this tin y device supports complex both feature a Cortex-MO+ for peripheral processors, this series of system s-on-
sensor processing applications while and security processing. These chips are chips (SoCs) allow the integration of
m aintaining a healthy b a tte ry life. rugged—built to operate in a temperature the application layer, com m unications
range of -40°C to 125°C—and are ideal for layer, and m etrology functions in
• Arm Cortex-M4 Processor w ith FPU power-critical applications. The image, a single device. The specifications,
up to 100MHz specifications, and datasheet are for the image, and datasheet provided are fo r
• 1MB dual-bank flash w ith e rro r dual-core XMC7200. the PIC32CXMTSH.
correction
• 200KB SRAM (160KB w ith ECC • One or tw o 350MHz 32-bit Arm • A pplication/host core: Arm Cortex-
enabled), optionally preserved in Cortex-M7 CPUs, each w ith: Single M4F running at up to 200MHz
lowest power modes cycle m ultiply; Single/double- (application/host core)
• EEPROM em ulation on FLASH precision floating point unit (FPU); • 16KB ITCM/I-Cache, 8KB DTCM/D-
• 16KB unified cache w ith ECC 16KB data cache, 16KB instruction Cache
• Dual or single supply operation, 1.7V cache; Memory Protection Unit • MPU
to 3.6V (MPU); 16KB instruction and 16KB • Com pliant w ith IEEE 754, ANSI
• Wide operating tem perature: -40°C data Tightly-Coupled Memories (TCM) C12.20-2002, and IEC 62053-22
to +105°C • 100MHz 3 2 -b it Arm Cortex M0+ CPU • Up to 2MB embedded dual plane/
• Flexible clocking schemes • Inte r-p roce ssor com m unication in dual boot Flash
• Power m anagem ent m axim izes hardware • Up to 512KB embedded SRAM
uptim e fo r b a tte ry applications • Three DMA controllers • M etrology/coprocessor core: Arm
• Up to 42 General-Purpose I/O Pins • Integrated memories: 8384KB of code Cortex-M4F running at up to 240MHz
flash with an additional 256KB of work • S ym m etrical/asynchronous dual
Analog Devices flash; Read-While-Write (RWW); Single- core a rchitecture
www.analog.com and dual-bank modes (for Firmware • Energy M etering Analog Front End
Update Over the Air); Flash programming (EMAFE) w ith single- and dual-phase
through SWD/JTAG interface m eter support
• 1024KB of SRAM
Microchip Technology
Infineon Technologies www.microchip.com
www.infineon.com
DATASHEET URLS:
Datasheet:
32-Bit Microcontrollers
DATASHEET URLS:
Cost-Effective and Accessible Efficient 32-Bit Solutions for Ultra-Cheap MCU for
MCU Power Electronics Industrial Applications
STMicroelectronics has premiered Texas Instruments' TMS320F28003x The CH32V003 MCU from D
its most affordable 32-bit MCU yet: belongs to the broader C2000 family WinChipHead (WCH)—a brand affiliated A
T
A
the STM32C0, built around the Arm of scalable, ultra-low latency real with Nanjing Qinheng Microelectronics S
H
32-bit Cortex-MO+ with up to 48MHz time MCUs. These devices are intended Co., Ltd.—is based on the QingKe E
E
frequency. This cost-effective device for efficiency in power electronics RISC-V2A core. These ultra-affordable, T
makes 32-bit capabilities accessible solutions needing high power density, industrial-grade devices are suited to
to all developers, bridging the gap high switching frequencies, and with general purpose applications, with wide
between 8- or 16-bit MCUs and higher- support for GaN and SiC technologies. voltage, 1-wire serial debug interfaces,
performance 32-bit MCUs. Sharing Example target applications include low-power consumption, and an ultra
the same platform as the STM32G0, motor drives, appliance es, hybrid/ compact package.
the STM32C0 offers up to 32KB flash electric/powertrain systems, solar
memory and 6-12KB RAM. There are a and EV charging, digital power, body • QingKe 32-bit RISC-V2A processor,
variety of 8- to 48-pin package options, electronics and lighting, and test and supporting two levels of interrupt
with dimensions as small as 1.70mm x measurement. nesting
1.42mm. • Maximum 48MHz system main
• TMS320C28x 32-bit DSP core at frequency
• Arm 32-bit Cortex-M0+ CPU, 120MHz • 2KB SRAM, 16KB Flash
frequency up to 48 MHz • Programmable Control Law • Power supply voltage: 3.3/5V
• -40°C to 85°C/105°C/125°C Accelerator (120MHz) • Multiple low-power modes: Sleep,
operating temperature • On-chip memory: 384KB (192KW) of Standby
• Memories: Up to 32KB of flash flash (ECC-protected) across three • 1-channel general-purpose DMA
memory with protection; 12KB of independent banks; 69KB (34.5KW) controller; op-amp comparator; 10-
SRAM with HW parity check of RAM (ECC-protected); Dual-zone bit ADC
• CRC calculation unit security; Secure Boot and JTAG Lock
• 2.0V-3.6V • Clock and system control: Two WCH
• Low-power modes: Sleep, Stop, internal 10-MHz oscillators; Crystal www.wch-ic.com
Standby, Shutdown oscillator or external clock input;
• Clock management: 4MHz-48 MHz Windowed watchdog tim er module
crystal oscillator; 32KHz crystal • 3.3-V I/O design
oscillator with calibration; Internal • System peripherals: 6-channel Direct
48MHz RC oscillator (±1 %); Internal Memory Access (DMA) controller;
32KHz RC oscillator (±5 %) 55 individually programmable
• Up to 45 fast I/Os, all mappable on multiplexed General-Purpose Input/
external interrupt vectors Output (GPIO) pins; 23 digital inputs
on analog pins; and more
STMicroelectronics
www.st.com Texas Instruments
www.ti.com
DATASHEET URLS:
to fo im w In
r p a
e a y th
a n le s
s y m to is
il
y o e a
n c rt
in th
t o
te e th n ic
g r v le
sp W o e im g th to co th lo te fe (F q co is a te w e p a a o b m e e ,
n x o e e o m e S u n lg m a x o p vo n u ra rt I
a u
e
ciS
o
,
fi
H
A
T
e
w
it
m
p
p
o
rt
a
o
v
e
m
o
ch
o
o
rs
e
,
d
e
p
.
H
e
p
e
d
b
a
T
h
e
F
,
a
ls
a
d
ra
tr
o
l
m
o
o
ri
th
p
e
v
e
le
n
e
tr
m
in
t
fo
p
lic
a
id -o
ff
ild
in
g
O te ic
ro
fi
n
a th d
ca h le
n r si
g n
ra ck se o ti m
st
m
ra
g e r
ti ra co
. o c l e is
w st se th n tu , c tu ly o tt n T c c
lly
h IS a o t so p e ce e e co th a n n o o u
a m f m o fr o , re a x
kn re m h re lo
lin tr yp e n
o o n
e
re
d t h
co
p o te f o n a o g
th a w la g ic co co in
e d s
e A ic o n e u m m a n d m w u o m re is n s
is lle a m
ve n tr e s s
w si la e m n d d e a r n m o in
si
g
is T ro
d b p e th p la s o is p n r ro lly m tr f o w
is
e a r in e
te o a e le a n a o o
co th , s, o a
n H co to to p u o th
m
to th
e a n ra si se f s s r
ca ly ty i d n n a th n h l. n e
ll
e
ta
d E u c n
th ra
p th su re
a p n p
rt ti se
o i tr d t o y it n e
tr ti e tu e e fo o a ca d o e e t m y h
th R o se o so re ll (L
b ic o l a e ca x p B o
r.
c
Q
rm
so e M lle n th
p re ra fi m re u le e P a f n —
lli
n
th n
co
a la a in o A a e
rm in s e rs a tu rs e p R lly th p d g e n m si d st u n
I r. o t n n
se ) u ID o if a tr p
te c u r
S a in ry is rt
s
se re e la
o m e w o p ft m is
h
t is n t e so se e
st
a o th
se cc
l le s, st o p e E
a to T se th
co
d m
ce r d co o so b n tp o a h a ri p S e
to
t r O
si
m o ca so co m w m , n
r,
e e o u is e p e u r
le f e r. n p it a e e
fu re lu a le n lg
a p s la
ro P a rs
it ? R p ct o
ta
o h n ll su tr
o ti w te in t o cl r
re s
s I le p
th lo T tr
o n ty co o st o a t. fo ri im te lic je 3 u .
t ? in
e e g h l e
in re
p
t)
.
ch lle m n a u n m rs a is ty a 2
g rm e n e
st
a . b tp p A r th
a , ti p c d I
re s' co
o
ra s, re p lia
a
r. p ts
e h m a o te e
re
b T le u te n
-S
m
th te y
t. e
si a n n ti is b ro ts o s lic h t n s m s in m
st fi e o u a je e le f B a e o to ra
o st is d o 2 x
a r g , n to
t re ch n fe a u p fo tu e a
co p f g , e p
n e u a , r. ct o e e e t te e r a re n so in e
n o m
co n g d lin o d co ch re re si tr ra co b n
ce si ra
d so I n is
se
n o a b n
ra
b n si m o o cl n
th
u
la
st ti m w e a , n u a e th a ti o ie ic s p l n u tu t
o o a o n o
tr
o g ti
v a e n tr
o n v se h fo . d tr
o is t in
si r n n e ill f y f in l h e ck r- r d l g th e t e to le A e re
l in
r a th
a e to th
h rt e
re th a T th T m re n T g se w th p e th m te th C u te te o re m re a
e n e e H
se
o o C re h e
ch
x a e m e e m m u a
se ic id ir
si m si t R n a ra
n a ls
su se si si n e
rm d m r Y
E re m . a si ic n N c
tr
e p T a p p n le
o
p m o st t h n iu u si
st ic g st st a te
a R o o a T n ch
e o ti
c m s e s lly e e o a o ti ,
n is P e i u n lik o g m a te a O re C R n fa v y m p
o ra st M e
r. d th
n e ra
e
ra ra rs e is e
ce to d F e e a a g m h l ly .O th tu si (p
x tu tu ce ct o p
si t o w
r I u a o w a rm p k e o O a st i p p u a to u e
rs o th m
ti u e ra
w . v re s ill S ct r ch p e w e O t re a s re re re a re re
a
e T o so
e it
h ie is lic s in re sm
lO th . n /° s rs te s ti
r rm c m s
ra ra
ill O lid x v to a m
th a O e F e C
ss co
n st th m h o
F p a th e r ti re th e ll o e e e e o e il
d o
T C to typ
e o R a -s m e o a a T
is fi r a
). d ff g a f p o y
tu n
e r m e p n tt si n C
to a re e ic e d
rm e u
ic st
e
ta th is
. e st n p x
is n
t in . y re ra a
B R is
le re
cr p ffi c a . te sa is a a a
r. d e si
a ie T ld tr
e a E , m , T rs
n m r st m p n h a si to tu a n
a n e ci h lly
H d a e h m a a t a t is s st v d
ra e o
o e a re e w ce e a d n p ff o rt o o rs re b n a
se tu n A th m re o
ce
a k e c le e s f p e s
N t es h vi si rt n e g e
sp
o rs to s
T re a V ce e a
th st fo rs is a s s , ct
e te p re e ss
ch la lu
o
a C
s ve , rm te e o re e o in
re
e w a d ll e ci tr so a
n
a e m
(N IO
m rm r th it T r si
fi ib y b te .
is ri , in ft
e e o C m st le m g
th t C T fr
R a a is w n va h C n R b u a ca
h e e le d I e
e h
o C o tw
e ) m n
to ls it fu
a re a e 't y s ill n ti w a s
e o u r to h n m
lu rd ls o io ce o rd e
ff a r n te e si ch f n n it
h x (F
te rm ic t : fa ca s a y u . st iu 1 te ig
m is ie h n a is m a to a 0
ch h
p
(T is in to n
n e
fl
a
ct
u v e p
ch In n
s. n 0 a o e C u
p to b st e n e u g n w r R ca a t, re
t rm N vo
e
re e a
ty ry o sm ce T e p g d )
ke
b
e r,
r i g d n p u ra re se h p e m e a
lle ce e u 1
a (P s a rs m d ic p g a a w a m m s g n d p t
tu t w a a a o h tu
o a t o u d
rt ).
T to itv it d , re lle lit
n s /° re th a th th A
re h e C rs e o h e rd lly o a y a is re C in ch e is e in e e
) f r r, , 't ll
circuitcellar.com 39
rises. PTC is the opposite: the resistance most often are resin-coated and glass-
will increase as the temperature increases. encapsulated. If you want something that
Broadly speaking, you will encounter the use of has a fast response time (within seconds)
NTC more often. I am not sure exactly why that and comes in a compact form factor, a glass-
is. I suspect it's because they can be used not encapsulated thermistor would be the way to
only as temperature sensors but also as inrush go. They also tend to have a wide temperature
current limiters. That's right, a thermistor can range and great long-term stability, and they
also be used as a protection device. eliminate errors in resistance readings due to
For example, where I work, we ran into moisture penetration. But they cost more.
an issue with a replacement pneumatic pump Other types of thermistors come in their
FIGURE 1
that had a high inrush current that exceeded own metal housing, or even with a ring
The typical symbol for a thermistor
the maximum current specification for the terminal for easier installation. But because
switching regulator. Since we're in the middle these have more thermal mass, it may take
of a supply chain nightmare, we couldn't longer to detect a change in temperature.
easily select a different pump. Instead, the If you're monitoring the board temperature,
next simplest solution was to use a beefy NTC thermistors are also sold in typical surface
thermistor in series with it. When the pump mount packages such as 0603.
turns on, the resistance is high enough to
snub out the current transient. But about 10 METHODS TO EXTRACT
seconds later, the current running through the TEMPERATURE
thermistor causes it to heat up, which lowers Since, in a thermistor, the relationship
the resistance and causes the pump to go into between resistance and temperature is non
its proper, steady-state operating current. It's linear, we need creative conversion techniques
interesting because most parts in electronics once we obtain the resistance value in our
C
need to be cool to work well, but the thermistor circuit. One way is to try to pound the NTC O
L
here needed to be a certain temperature (it curve into something more linear so we can U
M
grew hot enough to be uncomfortable to touch) obtain the temperature with the equation of a N
S
to achieve proper operation. line with a negative slope. A common way to
Figure 2 shows both NTC and PTC behavior do this is by placing a resistor in parallel with
in general. It's important to understand the thermistor. This works well when trying to
that the relationship between resistance work within a narrow temperature range and
and temperature is not linear. This is a you can tolerate a little bit of deviation in your
disadvantage of thermistors compared to estimated temperature from the actual value.
other temperature sensors. For example, A table is another way to convert from
some temperature-sensing ICs have a resistance to temperature. Many manufacturers
proportional output. It's more challenging of thermistors will supply a graph of the typical
to extract temperature information from a response and an accompanying table of values.
thermistor, as we must use some non-linear If the data points provided are a few degrees
measurement techniques. apart, you can interpolate an estimated
Thermal Time Constant: Notice that I temperature between these points with a
mentioned in the inrush current limiting reasonable degree of accuracy. Both of these
example that it took about 10 seconds to techniques are great when you don't want to
reach the final steady-state value. There is deal with a complicated formula and are fine
a lag in how fast a thermistor can react to a with some error in the final measurement.
temperature change. This is called the thermal The next best way to get a more accurate
time constant. To quote the technical definition result involves measuring the resistance
provided by Littelfuse [1], the thermal time
constant is "the time required for a thermistor
to change 63.2% of the total difference
between its initial and final body temperature
when subjected to a step function change in
temperature, under zero power conditions."
It provides a good feel for how slow your
temperature measurement will be. I say "good
feel" because the thermal time constant can
be slower or faster depending on the medium
(for example, still air versus moving air).
TYPES OF THERMISTORS
Depending on your application, you have
FIGURE 2
a few choices of thermistor packaging. The
These charts depict NTC and PTC thermistor behavior. Notice how the relationship between resistance
two types of thermistors you come across and temperature is non-linear.
CIRCUIT CELLAR • ARPIL 2023 #393
values in a temperature-controlled setup to the such trouble, and instead turn to curve-fitting
resolution you require. Say, for example, you equations to reduce measurement error.
have a temperature chamber and need your Enter the Steinhart-Hart equation, a model
therm istor to function between 10°C and 50°C, of the resistance of a semiconductor at different
at a resolution of 0.5°C. You can set up your temperatures. The equation was first published
therm istor at 10°C and then take the resistance in 1968 by John S. Steinhart and Stanley R.
measurement, and then at 10.5°C and take Hart to provide a way to easily calculate the
another measurement, up until you have made temperature based on the resistance. I'm sure
it to 50°C. Though most people will not go to this was a godsend at the time, as computers
were of course not easily accessible.
FIGURE 3
This is the 10K Precision Here is the equation:
Epoxy Thermistor 3950
1 = A + B ln(R) + C(ln(R))3
NTC from Adafruit. They
are nice enough to also
include a bias resistor.
R is the resistance of the thermistor (in
ohms) at temperature T (in Kelvins). For the
mathematically astute, you will notice there is
no squared term on the right-hand side of the
equation. I never gave this much thought until
I started to write this article. It turns out that
including a squared term (say, D(ln(R))2 , for
example) causes the temperature prediction to
be less accurate. This is odd, as usually more
terms result in a better curve fit. But others have
FIGURE 4 verified this. So, if you were thinking of being
Thermistor wired up to a ESP32-S2- clever by adding it in, you'd actually be making
DevKitC-1 development board. things (slightly) worse. It's worth pointing out
that adding higher power terms after the cubed
term will result in a better approximation.
To use the equation, you need the coefficients
A , B, and C, and voila, you are ready to start
calculating away. If you have zero data on the
thermistor you intend to use (well, you need to
at least know that it is an NTC type), you'll need
to precisely bring the thermistor up to a chosen
temperature, on three separate points. I think it
is safe to say that most of us don't have a super
stable temperature chamber at home, so the
manufacturers that care to make more sales will
publish this data for you. The ones that really
care will give you the coefficients themselves.
But manufacturers will sometimes give you a
different parameter, 0 (beta), instead of the A,
LISTING 1 B, and C coefficients. This is for a completely
#include < stdi o . h>
These are the header files to be different (and less accurate) formula:
# 1nclude <s td 1i b . h>
used with our thermistor example.
# i nclude <math. h>
An interesting header here is the
# 1nclude “ freertos/FreeR TO S.h”
one used for ADC calibration.
# 1nclude “ fr e e r to s /ta s k .h ”
# i nclude “ d ri v e r/g p io . h”
# 1nclude “ d ri v e r/a d c . h” This formula aim s to achieve the same
# i nclude “ esp_adc_cal. h” results: for a measured resistance, we can
calculate the temperature.
R o is the resistance of the therm istor
Additional materials from the author are available at: (in ohms) at room temperature. And just
www.circuitcellar.com/article-materials like in the Steinhart-Hart equation, R is the
resistance of the therm istor (in ohms) at
References [1] and [2] as marked in the article can be found there.
temperature T (in Kelvins). As you can see,
RESOURCES
this equation is a bit simpler, and I believe it's
the more popular of the two as I see the beta
Adafruit | www.adafruit.com values published more often than the A , B r
Espressif | www.espressif.com
and C coefficients in therm istor datasheets.
circuitcellar.com
/ / ADC c o n f i g u r a t i o n p a r a m e te r s
WIRING IT UP s t a t ic e s p _ a d c _ c a l_ c h a r a c t e r is t ic s _ t * a d c _ c h a rs ;
As I have done in the past few articles, I'll s t a t ic c o n s t a d c _ c h a n n e l_ t CHANNEL = ADC_CH ANNEL_6;
use an ESP32-S2-DevKitC-l to demonstrate the s t a t ic c o n s t a d c _ b it s _ w id t h _ t WIDTH = ADC_W IDTH_BIT_13;
code. In order to get a resistance measurement, s t a t ic c o n s t a d c _ a t t e n _ t ATTEN = AD C_ATTEN _D B_11;
we need to place the thermistor in series with s t a t ic c o n s t a d c _ u n it _ t UNIT = A D C _ U N IT _ 1 ;
a bias resistor to form a voltage divider. By
/ / T h e r m is t o r c a lc u l a t i o n p a r a m e te r s
using the internal ADC on the ESP32-S2, we can
s t a t ic con st d o u b le B IA S _ R E S IS T O R = 1 0 0 0 0 .0 ;
measure the output voltage. I chose to use a s t a t ic co n st d o u b le VS = 3 . 3 ;
thermistor the 10K Precision Epoxy Thermistor s t a t ic co n st d o u b le BETA = 3 9 5 0 .0 ;
3950 NTC from Adafruit [2]. The thermistor s t a t ic con st d o u b le TO = 2 9 8 .1 5 ;
is shown in Figure 3, and the setup is shown s t a t ic con st d o u b le R0 = 1 0 0 0 0 .0 ;
in Figure 4. By rearranging the formula for
a resistor divider, we obtain an equation for
LISTING 2
calculating the thermistor value: These are the parameters we'd like to be configured—a group for ADC and the other for thermistor
calculations.
R thermistor = Rbalance •
v —D'
^out
A B O U T THE AUTHOR
Joseph Corleto holds a M aster's Degree in E le ctri
Firm ware Im plem entation: The firmware
cal Engineering. A side from w o rkin g as a fu ll-tim e
example I wrote is no more than 60 lines long.
I tried to make it as simple as possible to make E le c tric a l En g ineer, he has a sm a ll b u sin e ss (B it
the implementation easy to understand. Bang G am ing LLC), w hich creates video gam e elec
Listing 1 shows the header files we need tro n ics hardw are, and is actively pursuing the cre
to make it all work. Other than the standard a tio n o f a p ro je c t-b a s e d vid e o c o u rse u sin g the
libraries typically associated with many C ESP32. He d e scrib e s h im se lf as an E lectrical E n g i
programs, we need the FreeRTOS framework, neering handym an since he has skills in firm w a re ,
the programming paradigm Espressif likes R&D, PCB d e sig n , PCB a sse m b ly, and a u to m a te d
to push on its user base. We also need the testing. You m ay reach him an ytim e via his em ail:
headers for the ADC, GPIO, and the header Corleto.joseph@ gm ail.com.
for ADC calibration. The calibration header is
r#
Starting @
s6 9 9 The Best Value in Test
Just Got Better!
RIGOL
www.RIG0Lna.com/DH01000
CIRCUIT CELLAR • ARPIL 2023 #393
interesting because it supplies us with data that we can use value in order to obtain the temperature measurement. Note
to look up the actual voltage associated with a measurement, that the equation was rearranged to make it possible to
which makes our readings more precise. program. The last bit of code prints out the value for us to see
Listing 2 shows some parameters we'd like to configure. in real time. This is where you can dip your thermistor in ice
There are two things we want to be able to easily change in cold water or spray it with your flamethrower to see the live
our firmware: ADC parameters and calculation parameters. change in temperature.
The ADC parameters are intended to easily change the place to
store calibration values, which ADC channel to use, how many SOME THINGS TO NOTE
bits of resolution we'd like to have, the attenuation of the ADC Would this setup be good enough for a final implementation?
reading, and which ADC unit to configure. The one parameter Maybe, but probably not. It would benefit greatly by having the
that might be a little confusing is the attenuation of the ADC voltage divider's output go to a voltage buffer to minimally
reading. In short, if the voltage to be measured is too large, the affect the measurement, as the ESP32 pin's input impedance
ESP32-S2 provides a way to limit the voltage to accommodate probably did. It would also make sense to place a low pass
this. Otherwise, you would need to change the bias resistor in filter in series to eliminate noisy measurements. The averaging
order to shift the voltage range to something the ESP32 can scheme could still be used, but an alternative is a Kalman filter
handle. The calculation parameters are intended to change the if the temperature of what you're monitoring changes quickly.
value of the bias resistor, the source voltage of the divider, the To further improve the measurement, the bias resistor should
beta value of the thermistor, and the values TO and RO. be of a tighter tolerance, or at least measured beforehand so
Onto the main loop in Listing 3. At the very beginning, we know its actual resistance. In addition, you can use a stable
we need to configure the ADC in order to have it function voltage reference or current source.
according to our setup in Figure 6. In our infinite loop, the ADC
is read many times in succession and then averaged in order to CONCLUSION
get a low noise measurement. Once the average is calculated, Measuring temperature with a thermistor can be a tricky
we can use a function with the ESP32-IDF to directly convert task if you're not familiar with the math and techniques that are
the ADC reading into the voltage value with the help of the typically employed. Hopefully, this article made you a little more
calibrated ADC values. From there, it's easy enough to calculate confident in implementing your own firmware for your next
the thermistor value. The final calculation uses the thermistor temperature-sensing project. Thanks for reading.
// Main loop
void app_main(void)
{
// Configure ADC + characterize ADC
adcl_config_width(WIDTH);
adcl_config_channel_atten(CHANNEL, ATTEN);
adc_chars = callocd, sizeof(esp_adc_cal_characteristics_t)):
esp_adc_cal_characterize(UNIT, ATTEN, WIDTH, DEFAULT_VREF, adc_chars);
adc_reading /= N0_0F_SAMPLES;
LISTING 3
This is the main loop, where we take ADC readings and perform all calculations of the thermistor and temperature. Values are printed to the terminal window.
circuitcellar.com 43
S ta rt to Finish
Biometrics ।
How Do I Know Ybu A re Who You Say You Are?
By
Stuart Ball
FIGURE 1
Photograph of the MIKROE-4347
fingerprint sensor. Photo courtesy
MikroElectronika.
iometrics" is any way of measuring an identical twin that DNA tests couldn't differentiate (See,
"everyone"
identification.
must have the biometric
characteristic, or else it isn't useful. In this context,
really means "most people." A person whose
fingers were badly burned in an accident may lose their
fingerprints. That doesn't negate the usefulness of
"biometrics," but here I'll concentrate on biometrics as used fingerprints, but it won't work for that individual.
to uniquely identify an individual. Permanent: Unless your hands are permanently injured
In this article, I'll look at a single biometrics method or disfigured by disease, your fingerprints don't change. DNA
and examine the strengths and weaknesses of using also doesn't change. Some diseases can cause changes to the
biometrics for identification. I'll present the details of the retina, though, so over time a retinal scan method might fail
circuit and firmware I used here, but the intent isn't to to identify someone whom it was able to identify before.
make a construction project. Instead, I want to use that as Ease of measurement: If you want to identify a murder
a springboard to talk about general principles. victim, you may not care if you have to wait a few days
for the DNA to be processed. But DNA isn't very practical
REQUIREMENTS as a means of controlling entry to a building ("Give us a
To be useful as a means of identification, all biometric blood sample and come back tomorrow..."). In order to use
methods must have some common characteristics. Let's biometrics to control access to a building, allow access to
take a moment to examine each of these. financial or medical records, or for other immediate use, you
Unique: A biometric method must be able to identify need a means of identification that is instant.
you from everyone else. In a family where all the kids have Reliable: A biometric system must reliably identify an
dark hair except for one who is blonde, people could refer to individual as that individual. If Sam puts his finger on the
"the blonde kid" (although the blonde kid might get tired of fingerprint scanner, it needs to identify rather than reject
hearing it). But in a classroom full of students, blonde hair is it. If Sam is in the system but it can't identify him, then
unlikely to be unique. Fingerprints are unique, as are retinal it's not working. The system must also reliably avoid false
patterns (the pattern of blood vessels in the retina of the positives; it must not identify Joe as Sam when Joe isn't
eye). The iris of the eye is also unique. DNA is unique unless even in the system. Rejecting people who aren't supposed
you have an identical twin. Most identical twins share the to have access is as important as allowing access to people
same DNA, so if you have an identical twin, it may be hard who are supposed to have it.
to determine which of you committed the crime. In fact, Both of these are extremely important in things like
criminals have escaped trial for crimes because they had biometric time clock systems—you can't assign Sam's
CIRCUIT CELLAR • APRIL 2023 #393
working hours to someone else, or fail to Capacitive sensors read the capacitance
credit Sam for the hours he did work. There between the ridges of the fingerprint and
are all kinds of potential issues if you get that the sensor. For devices like smartphones,
wrong. And of course, proper identification capacitive sensors have the disadvantage
is essential in financial transactions. The use that they can't (currently) be located on the
of masks throughout the COVID-19 pandemic screen. A capacitive-type sensor has to be
has reduced the accuracy of facial recognition separate. Capacitive sensors are passive in
systems, although some have performed the sense that they don't need to "illuminate"
better than others. the finger. Smartphones can have ultrasonic
Fingerprints are currently the most or optical sensors on the screen.
common means of real-time biometric The patterns in a fingerprint have different
identification, although facial recognition names. If a ridge makes a closed pattern, it's
may replace it at some point. Fingerprint a "whorl." There are "right loops" and "left
sensors come in three basic types: optical, loops," and a ridge that splits into two ridges
ultrasonic, and capacitive. An optical sensor is a "bifurcation." There are many variations
takes a "picture" of the fingerprint and in fingerprint ridges that make up the unique
compares it against a stored image. Optical pattern on your fingers. A fingerprint sensor
fingerprint sensors need a backlight of some has to capture enough of these to be able to
kind to create the contrast necessary to determine if a fingerprint matches one it has
read the fingerprint. Ultrasonic sensors are stored or is from a different finger. I'll take
functionally similar to optical sensors except a look here at an off-the-shelf fingerprint
that instead of reading a light reflection, they sensor to illustrate how they work.
read the reflection of an ultrasonic pulse.
The hardware is significantly different, of THE CIRCUIT
course, but both optical and ultrasonic read a Figure 1 is a photo of the MIKROE-4347
reflection captured in a sensor. capacitive fingerprint sensor from
* 3 3V
LJ2 H 33
VI 2 VQ n VDD1 -------------------------------------- P U f t t d M L -
2 31
VDO2 P F 3/CANOT)VSSI1F ffl/T 1C C P 1 H R C L K
3 C2 30
VDD3 P f 2 /S S H C W T 1CCPQ/ TROO
Inf __
VDO4 PF l/C tc x S S I I T k/ID C C P V TRD t U l C IS
28
PF WCOo/CANOR x N M IS S I2R V 1 0 C C P 1 J /U 1R IS
CONNH4
yr 60
VBAT PE 5/A JN 6/CAN 0 W l2 C S D A A J 5 T i
P! ^A im C A N O T O /rPC S Q A J^TO
6
VDDA P E 3/AINO
7
PE 2/ AIN 1
8
PE VA IN 2/U FTX
9
VDDCl P E ttA M W T T O
VDDC2 1
P D 7W M I/U 2 Tk JW T5 C C P 1
C3
P D M J 2 F W W T5 C C P 0
44
PDMJ6Tx/USBOOP/W I 4CCP1
43
P[>-VU6TO/USEWDM W I
P D 3 /A M 4 /S 5 I1 f x / S S C I x / W l X O M
P D Z W N 5 /S S I 1TOZSSI3RX/W T JCCPO
P D V A M 6 /K C 3 S D A/SS t1| 3 F o / w T 2 C C P 1
P D 0 M N r /l3 C 3 S C tJ S S i|3 )1 C lK W T 2 C C P 0
±1 osco
PC 7/CO 4J JTx/W T 1CCP 1
X1 PC&CO • V 3 T O W 11CCP0
12 M H z P C 5 /C 1 ^ J lC tS A J lT x A J 4 T x /W TOOCP1
R1 »K PC 4 /C 1 A ) 1R T S /U 1TO /U4TO /W TOCCPO
c*. 11
OSC1 P C 3 /S W O /T 5 C C P 1 /T O O
20 pt
P C 2/T 5C C P <¥T D I
PC W O I f f l M S n 4OCP1 SPS7 N O
PCC1/SWCLKJ 14CCPW TCK
*3 3 *3 3 •33 22K
Serial
FIGURE 2
Schematic of demonstration circuit
circuitcellar.com
MikroElektronika in Belgrade. I've seen the do my own testing— but it could be used as
same module from Adafruit and one or two the basis for a full application.
others, and it's available on Digikey. The The FW is written in C using the TI Code
manual for the module is from Hangzhou Grow Composer Studio software and the TI Tivaware
electronics, so all the vendors supplying this libraries, available on TI's website. The FW has
are likely getting them from Hangzhou Grow three modes of operation, set by a compile
or another common source. The manufacturer time variable named "Mode." It can either
calls the part R503 in the manual. capture a new fingerprint (Mode = C a ptu re),
The sensor is designed to mount on a panel sense a fingerprint and detect if it matches the
using the threaded portion of the body. Its stored fingerprint (Mode = Sense), or it can
black center section is the fingerprint sensing erase the fingerprint library in the 4347 module
area. That is surrounded by an LED ring that (Mode = E ra s e F In g e rs ). To change modes,
can be programmed to be red, blue, or violet. you must change the mode value, recompile
The LED can be on, off, blinking, or fading on the code, and reprogram the MCU. It's possible,
and off. In Figure 1 the sensor has a clear of course, to have all three modes available at
plastic cover, but mine did not include that. one time using a menu to select the mode,
Figure 2 shows the schematic of the circuit but that would require a more sophisticated
I used to interface with the module. It's based user interface which I didn't implement here.
on a TITM4C1233H6PM microcontroller (MCU), You could use the PC as a user interface via
and communicates with the 4347 module the serial port used for programming. I was
using the serial port. The board I used is a only interested in demonstrating the sensor
breakout board that I built for experimenting capabilities and the method of interfacing with
with the TM4C1233H6PM. It has quite a bit it. See the sidebar for a description of how the
more on it than shown in the figure—I deleted module is controlled by the FW.
from the schematic everything that wasn't After getting the sensor working, I did
relevant. some testing on it. It worked well after storing
Connector J2 is used for programming my left thumb in the sensor module. But if I
the MCU. Figure 3 shows the programming wet my thumb, it did not work at all until I
module schematic. This uses the same dried it. You may have experienced this with a
programming method as that discussed smartphone fingerprint sensor: if your finger
in my previous articles covering the TM4C is wet, it can't sense the fingerprint.
family of parts (see "Getting Started with I also tried a little Vaseline on my thumb
RTOSes: RTOS on an MCU," C ir c u it C e lla r to simulate what might happen in a machine
issue #381, April 2022, as an example). The shop or other environment where workers
programming module plugs into a PC serial could have grease or other substances on their
port or USB-to-RS232 module and uses the TI hands. The sensor had a lot of difficulty with
LM Flash Programmer software. To program that. If the sensor was used to control access
the device, you power up or press reset (SI) to a cabinet full of chemicals or essential
while shorting jumper W l; this puts the MCU tools, this could be frustrating to the workers.
into programming mode. After programming,
power-cycle the MCU or press the reset button OTHER CONCERNS
to start operation with the new firmware. Other considerations include a finger with
The 4347 module has all the fingerprint a Band-Aid due to a cut, or a finger that no
image recognition built in and can store up longer has a Band-Aid but has a scar. In
to 500 fingerprints internally. It senses when those scenarios, the individual might not have
a finger is pressed to the sensor surface and access. (A sizeable scar would likely confuse
sends the MCU a "detect" signal when that the sensor, although I wasn't willing to draw
happens via the blue wire on the cable. Under
MCU control, it can store a fingerprint, and it
can determine whether a detected fingerprint
matches one it has stored. The module comes
with a small 1mm pitch connector. I cut that
off and wired it to a Molex connector with 0.1"
spacing to make it easy to connect.
FIRMWARE
The firmware (FW) for the fingerprint
sensor is available on the C ir c u it C e lla r
article materials webpage for this article
(www.circuitcellar.com/article-materials). It's
not a full application—I included only enough FIGURE 3
features to demonstrate the capabilities and MCU programming circuit.
46 CIRCUIT CELLAR • APRIL 2023 #393
blood to test it.) If the environment requires case, you'd have to keep a hand cleaner and
that latex or other gloves be worn, those must paper towels next to the cabinet.
be removed and probably discarded before
using a fingerprint sensor. SECURITY
What if we have another COVID-like How do you securely add or delete
pandemic? Will the sensor be a distribution fingerprint templates? You must have a way to
point for the virus? There's no way to use do this. On your smartphone, you need both a
it without touching it. Iris and retinal scans password and a fingerprint if you are going to
don't have this issue—there is no contact use the fingerprint sensor. Something similar
with the eye. That is one potential issue with will be needed in other applications. A large
a fingerprint sensor, especially in a medical company may have IT add fingerprints for a
environment. specific lab or cabinet, and require the employee
Some of these issues are unique to this to present a company badge or other ID to
specific type of sensor, but they illustrate the enter their fingerprint. But some mechanism
problem of relying solely on biometrics for must be employed to prevent an unauthorized
identification. In most cases, you would want person from adding their fingerprint to access a
an alternate means of identification. Would controlled space or equipment.
you really want an employee to be locked out
of an essential cabinet because of a Band-Aid STORAGE
on their thumb? In some cases, you could The 4347 module can store a number of
work around it by allowing employees to use templates in its flash memory. Of course,
fingers on two different hands and to store the number varies with the size of the flash
two different templates for each person. That memory. The module allows you to query the
solves the Band-Aid problem, but maybe not amount of space available. I didn't implement
S the wet/greasy hands issue. Maybe, in that that in my firmware because I only stored one
N
M
U
L
O
C INTERFACING WITH THE 4347 MODULE
The MIKROE-4347 module provides some low-level • Set LED ring blue to indicate successful capture.
functions for interfacing. I'll reference the commands as (At this point the fingerprint is stored and can be used.)
they are named in the Hangzhou Grow reference manual, • If failure anywhere in the process, set LED ring red.
with a brief description, to show what's involved in using
the module. To check if a fingerprint matches the stored template,
The push button in the schematic initiates capture. you press your finger on the sensor. If it works, the LED
The code checks for errors, but I've left that out of this ring turns blue, and if it fails, the LED ring turns red. Here
description to make it simpler. Each command to the module is the algorithm:
is acknowledged by the module, and the software uses the
acknowledgment to check that the command was received If finger detected:
without errors. Look at the FW source files on the Circuit • Issue Genlmg command to capture fingerprint image.
Cellar article materials page for the details. If an error is • Issue Img2Tz command to capture scan in buffer 1.
detected, the sensor LED ring goes red. • Issue Genlmg command to capture fingerprint image
To capture a new fingerprint and store it in the module again.
flash memory, you press button S2 and hold your finger on • Issue Img2Tz command to capture scan in buffer 2.
the sensor. When the ring turns violet, indicating that the • Issue RegModel command to build template model from
fingerprint was captured, release the button, remove your buffers.
finger, then repeat. If the fingerprint identification fails, the • Issue Search command to see if fingerprint is found in
LED ring turns red. If it works, the LED ring turns blue. Here stored templates.
is the algorithm for this process: • Set LED blue if fingerprint is identified.
• Set LED red if fingerprint is not identified or if any step
If finger detected and pushbutton depressed and fails.
debounced:
You can see that there are a number of steps involved
• Issue Genlmg command to capture fingerprint image. in saving and then using a fingerprint. The demo code just
• Issue Img2Tz command to capture scan in buffer 1. allows one fingerprint to be stored, although the module
• Turn LED violet and wait for finger and pushbutton to be will store many. In a real application, you would probably
released and reasserted. look at the template number of the fingerprint so you can
• Issue Genlmg command to capture fingerprint image. record who accessed whatever it is the sensor is protecting.
• Issue Img2Tz command to capture scan in buffer 2. In the demo code, the template number is captured but
• Issue RegModel command to build template model from not displayed anywhere, and there is just one fingerprint
buffers. captured—so if a successful match is found, it has to be
• Issue Store command to save template in flash memory. that one.
circuitcellar.com
J f
E m b e d d e d in Thin S lices
PgBBggim Embedded
RealJim e Systems
cannot tell you how many times I have waypoint between these two locations. Paths
said: "If only I could duplicate the 1, 2, and 3 in Figure 1 demonstrate this. RNAV
bug, I could find it. And if I find it, I systems allowed planes to fly in straight lines
could fix it." But duplication comes by triangulating the flight path using multiple
first. We are wrapping up this series on VORs (which basically provided the angle or
debugging embedded real-tim e systems with heading to the VOR) and the distance to the
three articles: we are looking at duplication VOR waypoints (using an avionics box called a
strategies this month, and finding strategies Distance Measuring Equipment (DME) [1]. For
in the final two articles. example, RNAV allowed planes to navigate to an
airport that didn't have a VOR.
BOB'S TOP DUPLICATION We installed our RNAV in one of the Gulf
STRATEGIES Stream II planes (Figure 2) of a potential
Even once you know the kinds of bugs that customer with a fleet of business jets. A
exist ("Know your enemy."), and you have a big sale was dependent upon the successful
good set of debugging tools and know how demonstration of our product. The day of the
to use them, some bugs are still difficult to demonstration was rainy and foggy—perfect
duplicate and find. I want to propose some weather to demonstrate navigation to an
strategies that I found helpful in doing the airport that didn't have a VOR waypoint. Since
im possible—duplicating those bugs that are this article is on debugging, you can probably
impossible to duplicate. guess where this is going. Or perhaps I should
In all my years of debugging embedded say: where we were not going. As we came
systems, the worst are those you cannot out of the clouds, there was the airport—one-
duplicate. Many, many years ago, we had an area quarter mile to the left. Gulp!
navigation (RNAV) system design that seemed Duplicating that bug proved to be almost
ready for showtime. A little background: For impossible. Was it in the aircraft? Was it
years, airplanes navigated by traveling between in our system? Was it noise because of the
Very High Frequency Omnidirectional Range tem porary installation? Were the VOR or DME
(VOR) waypoints (Figure 1). A plane would signals at fault? This is the challenge with
not fly directly from NYC to LA, for example, duplicating the im possible—the bug can be in
but rather would zig-zag from waypoint to so many different places.
circuitcellar.com 49
HORSE IT
One strategy that I have employed
successfully over the years is what I call "horse
it." Though I've lived in the Northeast US for 50
years now, I grew up in the Midwest. I often
use a phrase or idiom that no one here in the
Northeast understands. "Horse it" is one of
those idioms. When I Googled "Don't horse the
car," I only found 14 entries across the Internet.
But all 14 used it the way I use it. So, somebody
out there knows that phrase [2]. I often say,
"Don't horse it," when helping someone get a
car out of a snow bank. That means don't overdo
the accelerator or get the wheels spinning.
In debugging embedded systems, "horse
it" means that you intentionally overdo it—
in terms of system inputs and environments. out, we made a hypothesis that certain writes
You overstimulate your system in an effort to memory were failing. To prove that, we took
to duplicate the bug. You can horse the about 10 units and modified the software to
environment, life expectancy, interfaces, user write to the flash 1,000 times more often than
input, network traffic, memory, real-time we were doing in the field. In two hours, we
usage, and whatever else you can think of to simulated one hour of life of the 20,000 out in
attempt to duplicate a bug. Let's see how this the field. Sure enough, the flash started failing
can help by looking at each of these from real in a few units after a few weeks.
C
examples that I've experienced. Much to our embarrassment, we found O
L
Horsing the Environment: Many of the a small footnote in the flash datasheet that U
M
systems we designed over the years were "recommended" using Error Detection and N
S
deployed outside. One time we started noticing Correction (EDC) software in the flash driver.
some solar energy systems (Figure 3) were Our Linux driver did not support this when
periodically rebooting. Although the data loss we first released the product. Thankfully we
was minimized because of how we designed it, didn't have to write it from scratch because a
it was still a problem that made our product new flash driver with EDC was subsequently
look bad. We noticed that most of the failures released. That made the fix easy to implement,
occurred in units deployed in the deep South but it required a kernel change for every unit in
or the Southwest during the middle of the the field. We had provisioned for making kernel
day. Something was going on at midday. It changes over the air (OTA). But it was the first
so happened that the peak current from the time we had to do so, and it was complicated.
solar panels also happened at the same time To horse a system's lifetime, a good
the temperature peaked. Was temperature resource is the literature on Highly Accelerated
causing the problem, or was the peak energy Life Testing (HALT) [3][4]. These techniques and
the problem? Our log files were not helping us strategies are used to expose bugs rather than
duplicate the problem, and the problem didn't duplicate bugs—but the principle is the same.
manifest when we ran the units in a temperature So learn the methods to perform HALT, and
chamber. So, we were not sure what was failing utilize them in your debugging.
when. By design, the system should handle the Horsing the Machine to Machine (M2M)
temperature and the current draws. Interfaces: I winced every time we had to bid
We took a heat gun (carefully directing the on a project in which a new M2M interface was
heat at one chip at a time so as not to overheat being developed by two different companies—
other chips) and were able to identify one IC that
was not meeting its operational temperature
specifications. It would have been expensive to
retrofit all the existing systems with new units
with chips that met their temperature specs.
So, our solution was that in hot and sunny
environments we installed a sun shade inside
the clear plastic housing. High-tech!
Horsing the Lifetime: We had a system
that started experiencing some higher-than-
expected returns after we had about 20,000 of
them in the field. We suspected that the flash
memory was failing, but could not duplicate it
FIGURE 2
in our lab. Gulf Stream II
CIRCUIT CELLAR • APRIL 2023 #393
each developing one side of the interface. We Thumper (like the bunny in the movie Bambi).
knew from experience that debugging those It was an array of solenoids configurable by
interfaces could be a nightmare. Was the position to push a button on an embedded
problem us, them, or the specification? device. We created a script language that could
Doing whatever you can to simulate "their" program a sequence of button pushes with
interface and then horsing it by sending various time delays.
significantly more data to your design than We didn't have the manpower resources
expected is a wonderful way to flush out needed to pound away at keypads and keyboards
problems. Alternatively, you can ask the client in order to adequately test our systems, so
to send you a lot more data or ask if you can Thumper was a much-needed product. When
send them a lot more data, with the intent of Thumper was working, it was wonderful to
horsing the system and duplicating the failure. watch it enter 10,000 new accounts, delete
Horsing the User Input: Early in the life them, and add 10,000 more again, many times
of our company, we created a product called in a row. But we weren't particularly good
FIGURE 3
mechanical engineers, and the product was a
LGate 120 Solar Energy Monitor complete engineering failure.
There are test tools out there that do this
internally. I remember that with the Palm
Pilot development tools there was a tool called
Gremlins that could flood your program with
both random user touches and canned data. It
was great for testing and debugging because it
"horsed" the system's user input.
Horsing the Network Traffic: If you find
yourself occasionally dropping packets or
getting scrambled data, you may want to horse
the network traffic. Double it, or create an
order-of-magnitude increase in traffic. Create
larger-than-expected packets. This is useful not
only in testing, but also in duplicating bugs.
Horsing the Real-Time Usage: I have talked
about the Apollo 11 navigation computer's real
time resource starvation problem in my Circuit
Cellar article "FreeRTOS (Part 1): Intro to Real-
Time Operating Systems" (Circuit Cellar #365,
December 2020). A good way to force a timing
problem to surface is to horse the real-time
usage. There are several ways you can do this.
You can put in a test task that hogs all the real
time, or at least puts it on the edge of real-time
starvation. You can modify an existing task to
hog most of the real-time. Or you can add lengthy
delays in your Interrupt Service Routines. Then
observe how the system responds. Is it resilient
and robust? Does it somewhat duplicate the bug
you've been seeing?
Horsing the Memory: Both dynamic
memory (heap) and the stack can be horsed by
reducing their size to see if you're experiencing
an out-of-memory or stack overrun condition.
If you reduce the stack size of all suspected
tasks or reduce the amount of heap, does the
problem happen sooner?
This brings me to one of our goals in all
horsing strategies. Another phrase I use with
all of these horsing techniques is what I call
FIGURE 4
"hasten the day." Our goal in trying to duplicate
IS glass bottle making machine
the un-duplicatable is to reduce the time it
takes for the bug to manifest itself.
Additional materials from the author are available at: Remember Bob's maxim: For every new
www.circuitcellar.com/article-materials order of magnitude of units you ship, a new bug
References [1] to [4] as marked in the article can be found there. will surface. Each one will be more complicated
circuitcellar.com 51
and harder to duplicate than the previous one. If you start CONCLUSION
shipping tens of thousands and hundreds of thousands of units, Before we can fix a bug, we usually have to be able to duplicate
they will be nigh impossible to duplicate. it. And that can sometimes be the hardest aspect of debugging.
I've found these three strategies helpful in replicating a bug.
AUTOMATE THE SCENARIO The first and most successful over the years was to "horse it."
In addition to horsing the system, I have occasionally found The second most useful technique was finding a way to repeat
two other useful strategies in duplicating an impossible-to- the scenario thousands of times—preferably in an automated
duplicate bug. If the bug manifests itself in a particular scenario, fashion. Finally, videotaping the operation in the field can yield
but you cannot duplicate it when you recreate that scenario, it's some surprising results that may help you duplicate the bug.
essential to find a way to automate that scenario so you can run How about you? What strategies have you found useful to
it many times. duplicate a bug in an embedded system?
Obviously, this will be different with every system and with Next time, we will cover faulty assumptions that we make in
every bug in the system. And generally, it's not easy. You may our attempt to find a bug. But as always, only in thin slices.
need to repeat the scenario thousands of times to duplicate the
problem. Then you'll need to do it again thousands of times to
verify your fix. Be as creative in figuring out how to automate ABOUT THE AUTHOR
the scenario as you were in designing the device.
Bob Japenga has been designing
VIDEO THE USAGE IN THE FIELD embedded systems since 1973.
One time, we experienced some failures in electronics located From 1988-2020, Bob led a small
on a glass bottle-making machine (Figure 4). Post-mortems of the engineering firm sp e cia lizin g
failures indicated an overtemperature problem. However, there in creating a variety of re a l
seemed to be no rhyme or reason for the electronics to overheat. tim e embedded systems. Bob
After videotaping the operation, we found that some has been awarded 11 patents in
C
machine operators pushed buttons on the machine with the many areas of embedded systems O
L
same tongs that they used to pull hot molten glass (>1000° and motion control. Now retired, U
M
C) out of it. Eventually, this caused the electronics inside the he enjoys building e lectro n ic N
S
button enclosure to far exceed the 125°C they were designed to projects with his grandchildren. You can reach him at
withstand. You will never know exactly how your customers will [email protected].
use your design until you watch them.
dataprophet
* f t
k. i ■mm
C o a l- o r ie n t e d ,
re su it s-d Riven
a n a Im p a c t f u I
\ \ “ fl
w w w .d a ta p r o p h e t . c o m
52 CIRCUIT CELLAR • APRIL 2023 #393
From th e Bench
By
Jeff Bach iochi
I
C involves audio files. The trouble is that one can use tape or vinyl).
many file formats to store an audio file [1]. In fact,
some are proprietary, and you are required to use THE DIGITAL WORLD
their hardware to play back any files saved, since they A micro can do everything perfectly in the digital
are stored in a format that isn't documented. While world, but when it comes to analog it is never quite
this isn't a problem for the device as is (since the perfect. That is because the conversion from analog to
hardware used in the device handles it well), it makes digital can never achieve perfection. We can increase
substituting a more capable system a real challenge. the amount of resolution (use more bits to represent
I first considered an attempt to understand this the analog value), but it will always be off by some
proprietary format. After some thought, however, it amount. Yes, the error can get infinitely small, but
became clear that the right approach would be to use it will never equal zero. Luckily, most of the time we
one of the open and available file formats. But which don't really need all that accuracy. Do you care whether
one? This brings us to this month's project. the temperature is 68° or 68.0486°? That need for
What type of audio file might provide the best accuracy goes for audio as well. If you are listening to
balance of quality and size and still be easily edited, music and have a decent stereo system, you are able
stored, and reproduced with a minimum of circuitry? to reproduce the original sound track to an exceptional
SD card storage offers an SPI interface to micros that level digitally. Although audio enthusiasts swear that
can access a large amount of file space. Let's use this to vinyl is still superior to digital recording, I can't tell the
provide playback of pre-recorded audio. Then let's look difference between a vinyl record and a digital CD of
into some of the most widely used audio file formats, the same content. Let's look at some of the possibilities
and decide which would work best for this application. when making a digital recording.
When you think about audio, you probably think Types o f Audio Formats: The standard audio
of a microphone or other source of sound production formats fall into two basic groups: compressed and
in the audible range. Our brains allow us to hear uncompressed. Compressed formats have two basic
frequencies from as low as 20Hz to as high as 20kHz, groups— lossless and lossy. Table 1 shows the common
but this depends on the relative loudness of sound, types of audio file formats.
measured in decibels. As we age, the decibel level we Uncompressed audio can be converted to digital
need to hear some frequencies increases, so we lose format without further processing. The uncompressed
the ability to hear those frequencies unless they are audio files tend to be the most accurate, but require
artificially boosted. a large amount of disk space—~34MB/minute for a
Today's hearing aids can boost the levels of any conversion of 24-bit (resolution), 96kHz (sampling
particular frequencies, restoring our perception to rate) stereo material. PCM (Pulse-Code Modulation) is
near-normal. Our eardrums vibrate when hit by audio a representative value of the sample. Most WAV files
waves—analog waves, like the ripples in a pond. Tape contain uncompressed audio in PCM format. The WAV
recorders and phonographs made it possible to store file is just a wrapper for the PCM encoding, making it
circuitcellar.com
YOUR CHOICE
When listening to a CD, we don't sweat the
fact that .WAV files are enormous. We can even
download them pretty quickly. However, if we
want to store them on some small, solid-state
device, we m ight be w illing to give up a bit
of fidelity to be able to store a larger library.
If the project we're w orking on is a low-end
toy, we would probably use one of the most
com pressive algorithm s, possible because
using sm aller m em ory devices = $aving$.
How much can we com press or convert a file
before playback becomes unsatisfactory?
Sampling Frequency: According to Nyquist
[2], the sampling speed of the ADC should be at
least twice the highest frequency of interest. CDs
use a sampling frequency of 44.1kHz (22kHz Cut
Off Frequency), FM radio uses a 32kHz sampling
frequency (16kHz COF), and AM radio uses a
22.05kHz sampling frequency (11kHz COF).
The sampling frequencies of digital editing
applications, such as Audacity, can range from
8kHz to 384kHz. So, the sampling frequency
makes a big difference in what frequencies
can be reproduced. Higher sampling rates also f i gur e 1
create larger files and how often the playback Audacity can aid in producing audio files. I used it here to generate a two-second audio file of a 1kHz
routine must transfer data to the output. sine wave. You can import and export files of many types.
54 CIRCUIT CELLAR • APRIL 2023 #393
.MP3 FORMAT
Bytes Length Content You can usually determine what kind of file
0-2
3 ) TAG Identifier. "ID 3 " = valid you have by the file's suffix. Other than maybe
a .tx t file, there is often some identification
3-4 2 TAG Version. Can be, for example, 03 00. w ithin the file that can help. For .mp3 files,
5 Flags there is a wrapper around the audio frames.
6-9 4 Size of TAG (total of all frames) A v l tag can be found at the end of the file's
audio data, and a v2 tag is found at the
10-? size Frames beginning of the file [3].
The general file form at for .mp3 is:
TABLE 3
The v2 tag is much more flexible than v l and is an open structure.
S [v2 tag] [audio frame 1]... [audio frame x] [vl tag]
N
M
U TABLE 4
L Bytes Length Content The firs t 3 bytes of a v l tag is "TAG."
O Each tag's frame identifies a
C Table 2 contains the characteristics of the
different type of data and is variable 0-3 4 Frame Identifier
in length. complete v l tag. The firs t 3 bytes of a v2 tag
4-7 4 Size of Data is "ID 3." Table 3 shows the v2 tag structure.
8-9 2 Flags Each frame of the v2 tag contains specific
10-? size Data information. The fram e identifier, like the
tag identifier, lets you know what kind of
inform ation follows (Table 4).
TABLE 5
Identifier Description You can see that a v2 tag can carry much
These frame identifiers indicate
more inform ation and each piece is not
what type of data will follow in the
limited in length like the 30 characters in v l.
data portion of this frame. Each is
TENC Encoded By The frame identifier indicates the type of data
optional.
WXXX URL that follows. Table 5 is a list of the possible
fram e identifiers.
TCOP Frame Identifier
When I created a two-second audio file, I
TOPE Original A rtist was asked to add some inform ation to the file.
TCOM Composer This was saved in the v2 tag area. I f we look
at a partial dump of the file in Figure 2 [4],
TCON Genre
the highlighted area is the v2 tag beginning
COMM Comments with "ID 3." You can pick out the seven frame
TYER Year identifiers used in this area.
Im m ediately following the v2 tag is the
TALB Album
firs t audio frame. The firs t four bytes identify
TPE1 A rtist it as an audio fram e (Table 6).
TIT2 Song Name From Figure 1 you can see that the firs t
four bytes of the audio frame starting at
0x85 are 0xFFF320C4. In bit form at that's
ABOUT THE AUTHOR O b l l l l l l l l , O b llllO O ll, ObOOlOOOOO, and
OxObllOOOlOO. The im portant inform ation we
J e ff B achiochi (pronounced BAH-key-AH-key)
need here is the values in Table 7.
has been writing for Circuit Cellar since 1988.
Using the Version and Layer inform ation,
His background includes product design and we can find the number of samples in each
manufacturing. You can reach him at: fram e (Table 8). In this case it's 576. Now we
[email protected], or at: can discover the remaining pieces of interest
www.imaginethatnow.com. (Table 9) and use them to calculate the data
length of the audio frame. We have what we
circuitcellar.com 55
2
s o u r /s c of an attempt to replace some inflexible and
StN/CMD
U1
4
CSJD3 closed hardware. The original hardware uses a
DI
?0 10
D2 serial flash device to hold audio files. These files
C1K 3V DET
21
22
SDC
d Y I
rs_.uV nU h
17 SDK} i
are packaged into a single binary file and stored
SD3
23
24
1015 cm 16
15
into a SPI flash chip. The compression algorithm
102
26
IOC
1 /V
14
13 LJ3A is proprietary and specifically designed to be
SU 1Z
28 iI n
12
11 £ LRC used as input to a sound processor. Since I
V i1 fj
29
IU Z f
FU Z (J
10
BCLK
DIN SPKR1
6
Is 11 am not designing with this sound processor, it
:u 9 9_
GAIN SPKR2
e
31 M^bl Ci
rzjy n
iit y m
7
50 just doesn't make sense to follow the crazy, yet
K JJZ G \D
33 6
IU Z 1
dw hr
1
S
VIN compact, structure of the original file storage
35 4 V A X OH 35 /
U
TXDO SVN
C u t)
Z3V 1
3 Opi»onl
device. So, I will make an executive decision,
1022
3/
38
HD23
GND
EM
j
ES/iH-irtrfiet
and instead of a serial SPI flash memory device,
S I'll use an standard microSD card. This allows
N E SP3? D E W IT
M USB the storage device to be easily programmed
U S
L A+ SP2
using a PC, and then to drop the files into a FAT-
O A- SPKR1
C 2
SO SPKR2
formatted directory structure.
vcc 4 -6 0
VSS
The size of a microSD card is about the
PA V 830 2
same as the SPI flash device. With a slight
O p l> 0ll2
J D A C /iU iM ifif t redesign of the physical port, the end product
will accept an SD card instead of plugging in
an SPI flash memory device. As it turns out,
FIGURE 3
This is a schematic showing the microSD card socket and alternate connections for using the internal
the SPI wiring to an SPI flash memory is the
DACs and an external audio amplifier or an external I2S amplifier. same as for an SPI microSD card. Although
I have to deal with the FAT file system, I
only need to read files on the ESP32, so the
// i n i t i a l i z a t i o n s e c tio n necessary commands are few and handled by
//define useDAC ESP32-audioI2S library.
//ifn d e f useDAC The ESP32 has four SPI peripherals: SPIO,
Audio audio; // cre a te an i2S in sta n ce of the audio lib r a r y
SPI1, SPI2 (HSPI), and SPI3 (VSPI). SPO and SPI
//else
are used internally to communicate with the
Audio a u d io (tru e , I2S_DAC_CHANNEL_BOTH_EN);
// cre a te an DAC in sta n ce of the audio lib r a r y built-in flash memory, and as such, you should
//end 1f not use them for other tasks. You can use SPI2
(HSPI) and SPI3 (VSPI) to communicate with
// in se tu p !) other devices. The audio library defines HSPI
//ifn d e f useDAC as the SPI bus to use. The default pins for this
audi o . s e tP i nout I2S_BCLK, I2S_LRC, I2S_D0UT); bus are sck=8, miso=9, mosi=10, s s = ll. Any of
//end i f the signals can be redefined prior to initializing
as shown in Listing 1.
When using the I 2 S bus, the three output
LISTING 3 lines needed are, I2S_BCLK=27 (BitCLocK),
If #define useDAC is used, the audio is set up for internal DACs. If the command is rem'd or I2S_LRC=26 (Left Right Channel), and I2C_
eliminated, the audio is set up using the I2S pins. DOUT=25 (DataOUT). Any of the signals can
be redefined prior to initializing (Listing 2).
Additional materials from the author are available at:
Because the internal DACs use dedicated
www.circuitcellar.com/article-materials
output pins, these happen to be the default
References [1] to [6] as marked in the article can be found there.
pins for the I 2 S, so if you need to use both I 2 S
and DAC outputs, you will need to redefine the
Resources
I 2 S pins. The alternate circuits for using I2 S
Audacity | www.audacityteam.org or DAC outputs for the audio are shown in the
Espressif | www.espressif.com schematic in Figure 3.
circuitcellar.com 57
/ / o p tio n a l
APPLICATION
This is enough of a framework for allowing * s t a r t - p r in t audio in fo ro u tin e
any of the audio clips to be played via direct
output through the DACs (and an external void a u d io _ in fo (c o n s t char * in f o )
amplifier), or I2 S output to a I2 S receiver/
amplifier. The SD has been formatted, and 12 i f ( verbose)
folders have been created on the SD card. Twelve {
audio clips have been recorded and labeled S e r ia l. p ri n t ( “ i nfo “ );
"clip0.mp3" to "c lip ll.m p 3 " in each of the 12 S e r ia l. p ri n t l n ( i n f o ) ;
folders (directories). The application allows a clip
number and group number to be set, or to play i f ( i n f o [ 0 ] == *F’ &&
the present "group#/clip#.mp3" audio file. i n f o t l ] == ‘ a ’ &&
Only slight m odifications are needed for i n f o [2 ] == ‘ i ’ &&
the application to handle both DACs and I 2 S. I i n f o [3 ] == ‘ 1 ’ &&
used a "define" statem ent (Listing 3), so you i n f o [4 ] == ‘ e ’ &&
can easily select the interface of your choice in f o [ 5 ] == *d ’ )
prior to compiling. {
The audio library can make use of three badFi1e = t r u e ;;
print routines for displaying operational
inform ation (Listing 4). I put some code into if( in fo [0 ] == *E’ &&
the a u d i o _ i n f o routine to recognize a few i n f o [ l ] == ‘ n’ &&
feedback strings to set Boolean flags, which in f o [ 2 ] == ‘d’ &&
I can use to tell if the file has not been read/ in f o [ 3 ] == ‘ ‘ &&
played correctly and if it is being played, i n f o [4 ] == ‘ o’ &&
in f o [ 5 ] == ‘f ’ ) C
when the EOF is reached. This way, I can O
L
turn off the verbose inform ation and just get { U
M
im portant feedback. endO fF ile = tr u e ; N
S
A sim ple user input routine prom pts to
enter G(roup), C(lip), or P(lay) to select and
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
alter the group# (folder), the clip# (file), or
play the present group#/chip#.mp3 file. The ★ end - p r in t audio in fo ro u tin e
fileName is placed in b u f and passed to via
a u d io . c o n n e c t t o F S ( S D , b u f) routine.
The library then takes com plete control of ★ s t a r t - p r in t id3 m etatdata ro u tin e
the transfer. To avoid using interrupts, the
comm and a u d i o . l o o p O is placed inside void a u d io _ id 3 d a ta ( const char * in f o )
the main 1 o o p ( ). Assum ing there are no long
delays in any routines, the library routines i f ( verbose)
can keep the transfer buffer full, decode {
samples, and pass the audio data to the S e r ia l. p ri n t ( “ i d3data “ ) ; Seri a l . p ri n t l n ( i n fo );
external amplifier.
CONCLUSION I i < i < 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
The idea here was not just to play audio ★ end - p r in t id3 m etatdata ro u tin e
files but to use the groups as different
environm ents. When the product moves
between environm ents, it will change folders, ★ s t a r t - p r in t eof ro u tin e
and a com pletely different set of audio files
will be used for that environm ent. I suspect void audio_eof_m p3(const char * in f o )
I'll need to come back to this from tim e to
tim e as I make progress. if(v e rb o s e )
For now, I hope you enjoyed learning a bit {
about audio files and the .mp3 file structure S e r ia l. p r i n t ( “ eof_mp3 “ ) ; Seri a l . p ri n t l n ( i n fo );
in particular. Using a little audio can make
your project stand out. Im agine actually
^ 'k 'k 'k 'k ^ 'k 'k 'k 'k 'k 'k i < c 'k 'k 'k 'k 'k 'k i < c 'k 'k 'k 'k 'k 'k 'k 'k 'k 'k 'k 'k 'k 'k 'k 'k 'k i < c 'k 'k
hearing dice being shaken in a dice cup, and
then the sound of them bones rattling across ★ end - p r in t eof ro u tin e
'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 'k /
the table. That would certainly make your
digital dice display stand out. See what you
can come up with for adding some sound to
LISTING 4
your next project. Until next time, too much The audio library can give back some interesting information via reading the v2 tag. I want to turn
to do, and so little time. that off, but still make use of any error or EOF info.
58 CIRCUIT CELLAR • APRIL 2023 #393
PRODUCT NEWS
WORLD
Technology Trending
at the World Ag Expo 2023
By Steve Prescott
AI-GRICULTURE
Most people think of tractors and big equipment
when they think about farming. While tractors have
been getting more high-tech over the years—with
sensors, digital controls, and GPS-assisted d riv in g -
other farm equipment has recently undergone
important digital innovations as well. And of
course, one of the most important developments
in recent years is the ongoing implementation of
artificial intelligence (Al) solutions in farming tech
to improve the accuracy, cost, and efficiency of all
sorts of tasks.
At the Carbon Robotics booth, I saw a large crowd
hovering around a 24-wide piece of equipment that
resembled a planter, but with spouts of fire flaring FIGURE 2
up from the ground beneath it. This turned out to be Control and circuitry inside Nexus' auto-weeding robot
PRODUCT NEWS
navigate and spray rows of crops. While recent technological FloraPulse tree moisture sensor and loT communication box
advances have significantly improved the accuracy of GPS, it
still doesn't work well under tree canopies, under which GUSS
frequently operates. GUSS's team solved this problem with
supplementary technologies like sensors and proprietary
software to help it navigate orchards.
PRODUCT NEWS
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 [email protected] with your file.
www.ccsinfo'.’com/CC323
PIC* MCU is a registered trademark of Microchip Technology Inc. in the U S and other countries
www.embeddedARM.com
UNLOCK CC 2022 T S -7 1 0 0
NXP i.MX 6UL 6 96 MHz ARM CPU w ith FPU
Our smallest single board com puter
measuring only 2.4" by 3.6" by 1.7"
JI
” Technologic
Sys trtNTlS **
62 CIRCUIT CELLAR. • APRIL 2023 #393
Answer 1-U nix 6th edition was initially Answer 3-John Lions, a lecturer
targeted to run on the larger members at the University of New South
of the PDP-11 minicomputer from Wales in Australia, wrote his "Lions'
Digital Equipment Corporation (DEC). Commentary on UNIX 6th Edition" in
Specifically, those that supported 1976. It accompanied an edited version
memory management, such as the PDP- of the source code that he also created.
11/40, PDP-11/45 and PDP-11/70. Together, these booklets spread through
the "underground network" to many
schools that were using Unix.
Answer 2—The operating system kernel Answer 4 —One feature that was
was written in just under 10,000 lines relatively unique to Unix was the concept
of source code in roughly 60 files. Only of a "pipe." What is a pipe, and why is
two of those files were assembly code; it significant?
the rest were written in an early version
of C.
Connect with
Q
E
Confidence
R
U
O Partnering with Digi for your loT
Y
S project can deliver exceptional ROI -
T
S
E from critical insights to cost reductions
T
www.circuitcellar.com/digi
circuitcellar.com 63
Deploying Al Successfully
in Manufacturing
identify previously hidden patterns and trends—to guide • how a digitally transformed business will operate.
production toward its optimal output (Figure 1). When A l • what will be required of staff.
connects an underlying control plan with a desired production • what the new model will deliver.
outcome, targeted production key performance indicators
(KPIs) can improve (for example, quality, throughput, or overall A study by Deloitte showed that organizations that invest in
equipment effectiveness). change management to a high degree are 1.6 times more likely
ML engineer Luyolo Magangane explains deep learning's to report that AI initiatives exceed expectations and more than
superiority for production optimization: "It comes down to a 1.5 times as likely to achieve their desired goals [6].
mathematical property. Artificial neural networks enable the
most efficient representation of any arbitrary mathematical THE AIAAS APPROACH: SYSTEMATIC &
function or probability distribution. The capacity to explain all HUMAN-CENTERED
interactions and interdependencies is not true for any other type The AlaaS approach first verifies that the full technology
of ML algorithm, but deep learning discovery is particularly well- solution delivers what it claims and can successfully integrate
suited for complex processes such as manufacturing." into the production workflow. Engineers and operators approve
Analyzing data collected from IIoT sensors, A l systems using assumptions about the manufacturing process and the
deep learning with prescriptive analytics are proven [4]. They incorporation method. Demonstrable proof of the AI solution's
increase yield and reduce product defect rates preemptively, tangible impact is the endpoint here.
significantly enhancing production efficiency and quality. After verifying that compliance and regulatory issues are
However, A l uptake in plants has been relatively slow compared addressed, the next stage involves the integration of the solution
with other industries. with actual operator workflows. Training helps operators work
with the system via, for example, a dashboard with prescriptions
DISSOLVING RESISTANCE TO A l ADOPTION generated by the AI software. Factory personnel then see the
AI adoption in manufacturing depends on collaboration results from the AI solution, and can ask questions and provide
between functional manufacturing experts and AI specialists. additional input. The AI application is thus integrated into the
While historical plant wisdom is invaluable, deriving additional plant's standard operating procedures.
value with insights garnered from historical data is impossible
without data engineers, data scientists, and AI algorithms. And TRANSFORMING MANUFACTURING VIA
the right AI implementation approach and adoption workflow RESULTS-DRIVEN COLLABORATION
are paramount. Reducing waste and rework and improving output and quality
The technology solution—Al-as-a-Service: Increasingly, is traditionally left to skilled and experienced manufacturing
businesses deploy infrastructure and software using the AI- specialists using standard statistical process control techniques.
as-a-Service (AlaaS) model (Figure 2). AlaaS allows industries But the volume of data generated in factories now exceeds the
to take advantage of AI products tailored to their specific use ability of engineers to process it.
case. Simultaneously, it saves them from investing in expensive Technology vendors offer new options that augment existing
applied science and software engineering teams. Only a simple plant wisdom. Knowledge sharing between engineers and AI
subscription is required. specialists can empower manufacturers to integrate data-driven
AlaaS solutions offer sophisticated software and technology decision-making into the shop floor.
infrastructure. They include near real-time support for the AlaaS solutions can handle, analyze, and leverage mass data
entire data value chain—from data capture to cleaning, storage, and prescribe actions for optimized production. Manufacturers
governance, security, analysis, and distribution of results. With who take a human-centric, collaborative, Al-enabled approach to
AlaaS, all the issues of data supply, software support, and optimization gain a distinct advantage—in driving production
infrastructure maintenance are ideally managed by the service lines toward peak operating efficiency.
Additional materials from the author are available at: ABOUT THE AUTHOR
www.circuitcellar.com/article-materials
Nicol Ritchie is a tech writer with extensive experience in long-
form thought-leadership content across a range of industries—
References [1] to [6] as marked in the article can be found there.
including financial services, digital advisories, and corporate social
responsibility. He holds Master's degrees in Applied Linguistics and
RESOURCES
Creative Writing.
DataProphet | www.dataprophet.com
® T D I<
pPOL™ Chip-Embedded
Power Modules
A Simple Solution for High Power Density Applications
Current Output: 3 A, 4 A, 6 A, 12 A
REGISTER FOR
Wide Input Voltage (up to 16 V) A FREE pPOL
EVALUATION
Adjustable Vout ±5m V
BOARD
Output Voltage, ±0.5% Initial accuracy (Up to 5 winners)
Powered by the NXP i.MX6 SOC with the Arm® Cortex®-A9
core, theTS-7970 industrial Single Board Computer (SBC)
stands out from the crowd with its high performance
components, connectivity options, and multimedia
capabilities. It's a general purpose, low-power SBC ready
to tackle demanding applications including digital signage,
HMIs, data acquisition, Edge loT, industrial automation,
and anything in between.
^ 8 0 0 MHz Solo or 1 GHz Quad Core Arm based CPU
to 2 GB DDR3 RAM
^4G B M LC eM M C Flash
TS-7970 ^ S A T A II, MiniCard, DIO, ADC, ModBus, USB, CAN
NXP i.MX6 Arm® Cortex®-A9 ARM CPU
^M ultimedia Solution with HDMI, LVDS, and Audio I/O
Single Board Computer
Made in USA
with Global Parts ^embeddedTS