This is only a preview of the May 2022 issue of Practical Electronics. You can view 0 of the 72 pages in the full issue. Articles in this series:
|
Max’s Cool Beans
By Max the Magnificent
Flashing LEDs and drooling engineers – Part 27
I
don’t know about you, but my
days seem to be slip-sliding away
under my nose ever faster. In addition
to my day job as a freelance technical
consultant and writer (‘I’ll write for
food’), I’m typically to be found juggling
a plethora of projects on the hobby front.
I’m also constantly being bedazzled and
beguiled by the scintillating selection
of ‘stuff’ that I randomly run across as
I meander (some may say ‘blunder’) my
way around the internet. To top things
off, I also have a short attention span
and I rarely get to finish anything before
something new and shiny comes along
to distract m... SQUIRREL!
Print your own
It’s not so long ago that electronic hobbyists had to capture circuit schematics
by hand and etch their printed circuit
boards (PCBs) using noxious chemical
compounds under exile in the bowels
of the basement. These days, by comparison, there are a variety of affordable
design tools available that allow hobbyists to capture schematic diagrams and
Fig.1. Meet the SV2. (Image: BotFactory)
Fig.2. James Bruton’s cunning creation.
48
create corresponding PCB layouts. Even
free tools like DesignSpark PCB (https://
bit.ly/3pBQuWE) are incredibly powerful
and sophisticated. In many cases, these
tools have capabilities that were the stuff
of dreams for high-end professional offerings just a few short years ago. And, once
you’ve captured your PCB layout, there
are numerous fabrication facilities clamoring to create affordable prototypes and
deliver them into your eager hands in a
timely manner.
On the other hand, in the same way that
you can use a 3D printer to create interesting doodads and thingamabobs at home,
there’s a lot to be said for being able to
fabricate your own PCB prototypes in the
comfort of your workshop (also known as
the dining room in my case, as my wife –
Gina the Gorgeous – rarely fails to remind
me). Well, by some strange quirk of fate, I
was recently chatting with the founders of
the BotFactory (https://bit.ly/35yQsYH).
Their latest offering, the SV2 (Fig.1), which
can sit comfortably on your workbench (if
not so much with your bank statement),
combines a conductive ink printer, solder
paste extruder, pick-and-place machine,
and reflow bed into a single product that
allows you to prototype your PCBs in a
matter of minutes.
At the other end of the scale, I recently
ran across an interesting little item called
Print-a-Sketch on the Hackaday website
(https://bit.ly/3vHdQOc). This little scamp
is a handheld device that lets you print
electronic circuits on almost any surface using conductive ink. By means of
an optical motion sensor (like the ones
employed by gaming mice), the Print-aSketch knows where it is and how fast it’s
going. This allows its control circuitry to
compensate for unsteady movement and
straighten out freehand wobbly lines, for
example, thereby providing a printing
precision of less than 0.5mm.
It’s life Jim, but not as we know it
As you are doubtless aware by now, my
chum Steve Manley plays a huge role in
many of the hobby projects I write about
in my Cool Beans columns in Practical
Electronics (PE). Steve is based in the UK,
while I hang my hat in the US, but the
wonders of the internet allow us to collaborate as though we lived just around
the corner from each other. To be honest,
Steve oftentimes does the bulk of the work
while I scamper around reaping the benefits (we all have our roles to play). As a
case in point, consider the animatronic
robot head we’ve been developing.
The way this all came about had its
roots in the tail end of 2021 when I created a couple of pseudo robot heads, each
of which used two of our SMADs (Steve
and Max’s Awesome Display) as eyes (see
PE, September, October, and November
2021). A little later (PE, December 2021),
our illustrious PE publisher, Matt Pulzer,
proposed that I add some sort of motion
to my robot heads. I’m no longer sure who
said what, when, or why, but – as part of
this – I ended up perusing and pondering an interesting Hackaday.com column
written by Danie Conradie (https://bit.
ly/3KjHzRv). In turn, Danie’s column introduced me to an ingenious automated
artifact created by James Bruton (Fig.2).
This little rascal (the artifact, not James)
is intended to provide a platform to implement lifelike animation. The problem
James set out to address is rooted in the
fact that hobby servos (which we will be
Fig.3. Meet our SMAD animatronic head. (Image: Steve Manley).
Practical Electronics | May | 2022
discussing in next month’s Cool Beans
column) move at a constant speed towards
their specified target. This isn’t an issue
for many purposes, but it can detract from
the sense of realism in animatronic applications. When you come to think about it,
very little bodily motion occurs at constant
speed. Instead, when we move parts of our
body like our head and eyes, those parts
are typically either accelerating or deaccelerating. If a loud sound occurs to one
side of me, for example, the muscles in my
neck will quickly accelerate my head in
the target direction and then slow it down
gradually as it reaches its desired destination. I have no doubt that the techniques
James describes will make their way into
our own animatronic offering in the fullness of time, speaking of which...
Holding my head in my hands
When we commenced work on our animatronic head, I started to experiment
with some simple off-the-shelf pan-andtilt mechanisms. Meanwhile, Steve fired
up his Fusion 360 integrated CAD, CAM,
CAE, and PCB software (https://autode.
sk/3hVxGNv). It wasn’t long before Steve
was using his trusty 3D printer to create a
thing of beauty and a joy to behold.
In an earlier column (PE, March 2022) I
showed photos of my rudimentary prototype platform and contrasted it to Steve’s
captivating control console. I also presented an image illustrating Steve’s awesome
approach to using two servos to provide
pan-and-tilt functionality for one of the
eyes. You can see an animation of this
movement on my Cool Beans Blog channel on YouTube (https://bit.ly/3GcVTJK).
As a slight aside, following that column
and having watched the video, PE community member Ken Wood, who is even
more passionate in his use of parentheses
than your humble narrator, emailed me to
say: ‘Hi Max, regarding your mate’s panand-tilt mechanism, as another approach,
articulated “attachments” on the far end
of an arm can be operated remotely by
push-pull through two Bowden cables
(the type of thing used for bicycle brake
cables, and even manual gearbox shifters
in cars instead of the complicated linkages used these days). The mechanism in
your article could place the eye swivel
away from the servos and have the servo
arms linked through Bowden cables (if
the servos are strong enough). Bowden
cables provide a DIY alternative to hydraulics (admittedly without the force
magnification) and (with careful design)
can be made to flex around intermediate
articulated joints (which might also be operated by more cables). The key is to keep
all the cables in the same plane, parallel
with the rotational axis, so that there is no
differential change of length as the joint
flexes. Even more interesting articulations
can be achieved by similar mechanisms.
Practical Electronics | May | 2022
Take a corrugated tube (ie, one that flexes)
and run four (non-sheathed) cables down
it (spaced around the perimeter). Pulling
on any one cable will cause the tube to
bend in that direction (like an elephant’s
trunk). Spiral the cables in opposite directions and the tube can be made to twist.
In this example, the cables are acting like
tendons and the springiness of the tube
provides the restoring force (like opposing muscles).’ Well, this is certainly food
for thought, but we digress...
Since that earlier column, Steve has
finished work on his animatronic noggin
(Fig.3). For your delectation and delight,
Steve has uploaded a video to YouTube
that presents this bodacious beauty in all
its glory (https://bit.ly/3sMi6Kk).
If you are interested in creating one of
these awesome artifacts for yourself, I will
be discussing more details regarding the
servo motors and breakout boards (BOBs)
we used in my next column. Also, Steve
has very kindly made his 3D design files
available. You can download a compressed
ZIP (file CB-May22-01.zip) containing
these design files from the May 2022 page
of the PE website (https://bit.ly/3oouhbl).
Next, we’ll work on the software, including our realisation of the lifelike animation
techniques presented by James Bruton discussed earlier. The fabulous news, however,
is that Steve very kindly created a second
SMAD animatronic head and control console for yours truly. Just a few days ago,
as I pen these words, this little rapscallion
arrived at my home, thereby placing me
in a position to proudly proclaim that I’m
sitting here holding my head in my hands
(which isn’t something you expect to find
yourself saying on a daily basis).
Don’t speak geek!
I’m sure you remember me mentioning my
chum Paul Parry on occasion. Paul is the
owner of Bad Dog Designs from whence he
creates marvelous masterpieces of a Nixie
tube nature (https://bit.ly/3sMFWps). Several years ago, Paul introduced me to Dr
Lucy Rogers, who is an author, inventor,
and a visiting professor of engineering,
creativity, and communication at Brunel
University London.
As I said in a recent blog: ‘Even if you
are the geekiest of geeks or the nerdiest of
nerds, speaking in the patois of the geek
is not recommended. I can’t tell you how
often I’ve seen peoples’ eyes glaze over
when I’m talking to them… and things are
even worse when I’m speaking geek.’ The
point of all this is I just heard Dr Lucy is
offering a suite of ‘Online Communication
Courses by a Person in Tech for People in
Tech’ (https://bit.ly/35xEG0w).
The way things were
These days we are spoiled by the power
and performance offered by digital computers. I still find it hard to believe that
it’s possible to purchase a microcontroller
development board like a Seeedunio XIAO
that’s only 0.93-inch x 0.69-inch (23.5 x
17.5 mm) in size boasting a 32-bit Arm
Cortex-M0+ processor running at 48MHz
with 256KB of Flash memory and 32KB
of SRAM for what essentially amounts
to pocket change (https://bit.ly/3IPpSc2).
This is a far cry from the way things
were in 1975 when I took my first tentative steps on the path to my BSc in
Control Engineering at Sheffield Hallam
University. At that time, the only digital
computer available to us was a monstrous
mainframe that lived in its own building.
I remember writing my first program for
this beast in a computer language called
Fortran (FORMula TRANslator). The initial step was to capture the code using
pencil and paper. Next, I keyed this program into a Teletype machine, which
converted each line of text into holes in
a punched card. I then hand-carried my
‘deck of cards’ to the computer building
and handed it over to some surly individual lurking furtively behind the reception desk. When I returned a week later, I
was presented with my original deck accompanied by a scrap of paper bearing
a hand-scrawled note saying, ‘Missing
comma on line 2.’ Arrggghh (and I mean
that most sincerely); couldn’t they have
added that comma for me? The end result
of this modus operandi was that it could
easily take most of a semester to get even
the simplest of programs to produce reasonable results.
The only computer that physically resided in the engineering department was
an analogue beauty, similar in nature to
the one shown in Fig.4. The idea here
Fig.4. Analogue computer, Lewis Flight Propulsion Laboratory circa 1949. (Image: NASA)
49
differences. Also, small initial errors can
be compounded and amplified from stage
to stage. Having said this, what may surprise people who haven’t used this type
of machine is that analogue computing
and analogue signal processing (ASP)
can be extremely efficacious when it
comes to modelling things like dynamic systems. As I recall, my first task was
to model how the insides of a refrigerator would cool down when it was first
powered up; also, how the internal temperature would change when the refrigerator’s door was opened.
The Analog Thing (THAT)
Fig.5. The Analog Thing (THAT). (Image:
Anabrid)
is that you have lots of small analogue
modules, each performing some function
like comparing two analogue signals to
see which is bigger (has the higher voltage), adding two analogue signals together, multiplying two analogue signals, or
integrating an analogue signal over time.
There were also a bunch of potentiometers (variable resistors) that were used to
establish coefficient values. The inputs
and outputs of the various modules were
connected using cables with jack plugs
on each end (unless you’ve done this
yourself, you have no idea how deucedly difficult it was to debug a setup that
wasn’t working as planned).
One of the downsides to this form of
analogue computing is lack of repeatability because – although they might
be in the same ballpark – the results
from multiple runs always have slight
50
The reason I’m waffling about this here
is that, as seen in Fig.5, I was just made
aware of a forthcoming analogue computer called The Analog Thing (THAT)
(https://bit.ly/370WEZH). I fear I must be
getting old, because I initially thought the
‘THAT’ was part of this unit’s name. It
took me several seconds to realise that
the ‘THAT’ was in fact an abbreviation of
‘The Analog Thing’ (colour me confused).
In addition to eight coefficient potentiometers, we have five integrators, four
summers, two comparators, two multipliers, and a panel meter. There are also
X, Y, Z, and U output ports that can be
used to drive things like an oscilloscope,
plus there are Master and Minion ports
that allow multiple THAT’s to be daisychained together to implement arbitrarily large programs. I must admit that I’m
sorely tempted to ‘splash the cash’ for
one of these little beauties. I find I have
a strange desire to create a convoluted
function and then spend an inordinate
amount of time debugging the rat’s nest
of cables. If nothing else, doing so would
take me on a trip down memory lane to
the days of my youth.
But wait, there’s more, because one of
the things that attracted me to the THAT
in the first place is that I’ve been contemplating a conundrum of an analogue
nature with respect to the potentiometers
(pots) Steve and I are using to control our
animatronic heads. We will ponder this
poser in a moment, but first...
Wandering into the weeds
You may have noticed that, to the untrained eye, I sometimes appear to wander
off into the weeds, taking a deep dive into
a seemingly random topic that tickles my
fancy, but don’t be fooled because there
is method behind my madness (honest).
In addition to being educational, fun, and
interesting in their own right, the projects described in PE are intended to provide the foundations for our readers to
develop their own circuits and systems
in the future. Similarly, when we present tips, tricks, and techniques to address
one situation, they are often applicable
to other applications.
Fig.6. Top-side pins for the Teensy 3.6.
As just one example, in an earlier
column (PE, October 2021), I described
a technique using 2-dimensional (2D)
arrays of 8-bit integers to define groups
of LEDs used to form patterns on our
SMADs. Two months later (PE, December 2021), I made mention of the fact
that a member of the PE community,
who we will call Simon (because that’s
his name), emailed me to say that reading my original column, and seeing this
technique, had proved useful to him
in creating an Arduino-based Morse
code trainer.
I only mention this because we are
about to take a short sideways tour into
a topic that may not appear to be tremendously important at this moment in
time. However, the techniques we discuss here will almost certainly prove to
be of use in the days that are to come.
Your other left!
A couple of months ago (PE, January
2022), I introduced the JH-D400X-R4
10K 4-axis joysticks we are using to
control our heads. At some stage in the
future, we plan on using sensors and
artificial intelligence (AI) to allow the
heads to control themselves (be afraid,
be very afraid), but that will be a tale
for another day.
In reality, the JH-D400X-R4s are 3-axis
devices with a pushbutton on top (their
creators imaginatively cast this pushbutton as a fourth axis of control). Each
joystick contains three 10kΩ pots, where
each pot is centered around its halfway
(5kΩ) position. If you move the pot around
any of its axes and let go, it will return
to its center position. Pushing the joystick forward or pulling it backward will
affect one of the pots. Moving it to the
left or the right will affect another of the
pots. And rotating it clock-wise or anticlockwise will affect the remaining pot.
The way we’ve currently got things
set up, by default, the left-hand joystick controls the head. Assuming you
Practical Electronics | May | 2022
are facing the head, moving
this stick to the left will cause
1
2
the head to turn to your left
(its right), while moving the
3
stick to the right will cause
the head to turn to your right
(its left). Meanwhile, push2
ing the stick away from you
(a) Symbol
(b) Pot
will cause the head to tilt up,
while pulling the stick towards
Fig.7. Pot symbol and
you will cause the head to tilt
graphical representation.
down. This way of working
makes sense to us, but it may not be intuitive to other users.
Also, we must consider the case where the operator is standing behind the head. This is why we included three toggle
switches on top of the control console – one reverses the actions of the left-right pan while another reverses the actions
of the up-down tilt: the third? I’ll never tell!
Still in the default mode, the right-hand joystick uses a
similar methodology to control both SMAD eyes simultaneously, making them look left, right, up, and down. However,
if you press the pushbutton on top of the left-hand joystick,
the head will remain in its current position and the system
will enter a new mode whereby the left and right joysticks
control the left and right SMAD eyes, respectively. Pressing
this button again will return the system to its default mode.
1
3
Why, Oh why?
When I originally commenced experimenting with the early
version of my animatronic noggin, I decided to use a Teensy
microcontroller (https://bit.ly/3J7pfeh). I opted for a Teensy
3.6 because (a) I like its features in the form of a 32-bit Arm
Cortex-M4F processor running at 180MHz with 256KB of
RAM, 1MB of Flash, 58 digital general-purpose inputs/outputs (GPIOs), and 25 analogue inputs and (b) I happened to
have one lying around.
The creators of the Teensy provide awesome pinout diagrams
(https://bit.ly/3J9lq8a). A cutdown version of the top-side pinouts for the Teensy 3.6 is shown in Fig.6 (digital GPIOs 40 to
57 along with analogue inputs A10, A11, A23, and A24 are
accessible via pads on the underside of the board).
I started by wiring the signal lines from the six pots on the
joysticks to analogue pins A12 and A13 on the nearside of
the Teensy and A14, A15, A16 and A17 on the far side. I then
created a little sketch (program) that cycled around reading
the values from the pots and displaying them on the Serial
Monitor provided with the Arduino integrated development
environment (IDE). I still remember the thrill of anticipation
when I grasped the left-hand joystick and moved it left-right
and forward-back, and I still remember the feelings of doom,
despondency, and disappointment when... absolutely nothing happened.
Fortunately, rather than going off half-cocked into a debugging rampage, I first tried moving the right-hand joystick leftright and forward-back. Oh joy! The numbers on the screen
changed accordingly. Next, I tried rotating both joysticks
clockwise-anticlockwise and – once again – the values being
displayed in the Serial Monitor updated as expected.
My trusty multimeter showed that all of the axes on both
joysticks were reacting as they should and that the expected
signals were reaching the Teensy’s inputs. It also didn’t take
long to determine that the two wayward axes were connected
to analogue inputs A12 and A13. Why weren’t these inputs
behaving themselves? I pondered possible points of failure,
but nothing leapt out at me. Eventually, rather than beat my
head against the wall, I simply unsoldered the signal wires
feeding A12 and A13, connected them to A18 and A19, and
everything worked as it should. Why, oh why should this be?
I have no idea. Obviously, I wouldn’t mind finding out (if
Practical Electronics | May | 2022
Fig.8. Reading pots 1x times.
you have any ideas, I’d love to hear them), but I’m not losing
any sleep over this because life is too short.
Baby steps
Just to ensure we’re all wiggling our derrieres in the same conga
line, let’s remind ourselves that a pot has three terminals (Fig.7).
Two terminals are connected to either end of a resistive element
(10kΩ in our case), while the third is connected to a movable
wiper. We’re using our pots as voltage dividers, so we connect
power to terminal (1) and ground (0V) to terminal (2), or vice
versa (it doesn’t really matter which way round these go because
we can easily manipulate the resulting readings in software).
If you are using a microcontroller like an Arduino Uno,
which is powered by 5V and whose GPIOs support 0 to 5V,
then you will use a 5V supply for your pots. By comparison,
although my Teensy 3.6 is powered by 5V, its GPIOs will only
tolerate 0 to 3.3V, so I’m using a 3.3V supply to power my pots
(this supply is generated by the Teensy’s on-board regulator).
The Teensy 3.6 boasts a 10-bit analogue-to-digital converter (ADC), which is shared between the analogue inputs. Ten
bits can support 210 = 1,024 different binary values, which
we number from 0 to 1,023. What this means is that the 0V to
3.3V signals on my pots’ wipers will be seen by the Teensy as
integers in the range 0 to 1,023.
Now let’s return to my program that loops around reading
the values from the six pots and displaying these values in
the Arduino’s Serial monitor (Fig.8). With respect to the LLR,
LFR, LRT, RLR, RFB, and RRT annotations, the first letter indicates the left (L) or right (R) pot, while the remaining letters reflect the axis in question: LR = left-right, FR = forwardreverse, and RT = rotate.
To be honest, when I was wiring things up, I didn’t spend
any time connecting specific pots to explicit analogue inputs
on the microcontroller because, as usual, this sort of thing is
easy to sort out in software. This explains why we start by
defining a constant value NUM_POTS to be 6 and then declare
an array of integers called PinsPots[], which we use to organise these inputs into the desired order:
PinsPots[NUM_POTS] = {A18, A14, A19, A17, A15, A16};
We also declare an array of integers called PotVals[], which we
use to store the values read from the pots. All this program does
is loop around calling two functions with a one-second delay at
the end of each iteration. The first function, ReadPots(), reads
the analogue inputs and stores the values in PotVals[], then
the second function, DisplayPotValues(), reads the values
out of PotVals[]and displays them in the Serial Monitor. The
heart of the ReadPots() function is a simple for() statement:
for (int iPot = 0; iPot < NUM_POTS; iPot++)
{
PotVals[iPot] = analogRead(PinsPots[iPot]);
}
51
any components we use should be physically
small and mounted as close as possible to the
microcontroller’s input pins.
Low Freq
H igh Freq
To be honest, you could write a book or two
From Pot
MCU
on this sort of thing (people have). For our purBand-pass
Band-stop
poses here, if we were to decide that capaci0.01µ F
1µ F
tors were the way we wanted to go, then – for
0V
each analogue input – we would add a pair of
capacitors (0.01µF and 1µF) in parallel (sideFig.9. Using capacitors
by-side) between the signal (analogue pin) and
Fig.10. Four fundamental filters.
to mitigate noise.
ground, and another pair between the signal
and power (Fig.9).
In my case, I decided that I really didn’t want to spend
The only reason this is of interest is because of the ways
my Sunday afternoon soldering capacitors onto my protoin which we are going to evolve it. As usual, you can downtype board (also, I hadn’t thought to reserve any space for
load this program from the PE website if you so desire (see
them), so I determined to opt for a software solution.
file CB-May22-02.txt).
VDD
0.01µ F
Low-pass
H ig h-pass
1µ F
Wibbly wobbly
Fabulous filters
Remembering that the pots in our joysticks default to their
center positions, we would expect all of the default readings to be 511. In reality, as you may have observed in Fig.8,
each pot has its own center value (LLR = ~506, LFB = ~520,
LRT = ~533, etc.), which is something we will have to account for at some stage in the future. Another aspect of this I
hadn’t considered is that when you move and subsequently
release one of the joysticks, it may not return to the exact
same center position. This is something else we will need
to cogitate on in the days that are to come.
But the thing I want to focus on here is that, even when
we aren’t moving the joysticks, the values wobble around
a little due to noise in the circuit and surrounding environment (eg, the RRT signal in Fig.8 varies between 509,
510, and 511). This noise could be coming from a variety
of sources, such as the power supply or electromagnetic radiation from other devices in the vicinity.
On the one hand, for reasons that will become clear, the
small amount of wobble we are seeing here isn’t important in
the case of our animatronic application. On the other hand,
I’m a digital man by trade (you know where you are with 0
and 1 values), and I find wibbly wobbly signals to be a tad
disconcerting, so I like to get rid of them given a chance.
I remember once joking to an analogue engineer friend
that it was strange how the wobbles always appear on the
least-significant bits (LSBs) and he quickly replied: ‘That’s
what these bits are for!’
I’m afraid we need to make a slight digression. In physics,
the term ‘frequency’ refers to the number of occurrences of
a repeating event per unit of time. Frequency is expressed
in units of hertz (Hz), where 1Hz is equivalent to one event
per second. This means that a lower-frequency signal (like
a man with a deep voice humming) has a smaller number
of Hz, while a higher-frequency signal (like me squealing
if I see a mouse) has a higher number of Hz.
If we wish to take a signal that is composed of a range of
frequencies and remove some of these little rascals, then
we can do so using some sort of filter. The four fundamental
filter types are low-pass (which passes low frequencies and
blocks higher frequencies), high-pass (which passes higher
frequencies and blocks lower frequencies), band-pass, and
band-stop (Fig.10). We can implement these filters in hardware or software.
Don’t be average
One solution to our problem is to take multiple readings
from each pot and then average them out (that is, sum ‘n’
samples and then divide the result by ‘n’). For example, we
might modify the heart of our ReadPots() function as follows (file CB-May22-03.txt):
for (int iPot = 0; iPot < NUM_POTS; iPot++)
{
PotVals[iPot] = 0;
Where’s the source?
Before we leap into action, one thing we might want to do
is see if we can determine the source of the wobbles, especially if we were seeing a substantial amount of noise. One
way to do this would be to move the joystick so that its
output reads 0, which means its wiper is at the ground end
of its travel. If we are still seeing the noise, then it’s probably electromagnetic in origin. Next, we move the joystick
so that its output reads 1,023, which means its wiper is at
the power end of its travel. If we are still seeing the noise,
then it may be originating in the power supply. In this latter
case, another quick test would be to swap out the power
supply for a battery; if the noise disappears, we’ve tracked
down the culprit.
Are capacitors the answer?
With regard to the readings we are seeing from our pots, we
can regard the wibble wobble on the LSBs as being (relatively)
high-frequency noise. One solution to the sort of noise we’re
seeing here is to add some capacitors to our circuit. Apart
from anything else, we want these capacitors to provide a
low impedance path to the fast edges and high-frequency
characteristics of electrostatic discharge (ESD) strikes, so
52
for (int iSmp = 0;
iSmp < NUM_POT_SAMPLES; iSmp++)
{
PotVals[iPot] += analogRead(PinsPots[iPot]);
}
PotVals[iPot] /= NUM_POT_SAMPLES;
}
In this case, we perform all of the reads on the first pot,
then on the second, then the third, and so forth. An alternative approach would be to start by taking a single reading
from each pot, then return and take a second reading from
each pot, and so forth (file CB-May22-04.txt). I’m not sure if
there is any official determination as to which approach is
the most efficacious, although I do have a ‘gut feeling’ that
the second technique may have a slight edge.
On the off chance you were wondering, what we are doing
here is implementing a very primitive form of finite impulse
response (FIR) low-pass filter. The reason for the ‘finite’
qualifier is that we are using a finite number of samples.
For the purposes of these discussions, I started by setting
NUM_POT_SAMPLES to 5 (Fig.11).
Practical Electronics | May | 2022
Fig.11. Reading the pots 5x times.
As we see, the results are significantly better than for our 1x samples, but
there’s still a little wibble wobble on
some of the signals. We could keep on
increasing our sample size – say using
ten samples – but this causes us to run
into a problem.
To control his animatronic head, Steve
is using a Teensy LC, which boasts a
32-bit Arm Cortex-M0+ processor running at 48MHz with 8KB of RAM, and
62KB of Flash. One big point is that the
Teensy LC has fewer GPIO pins at its
disposal, so Steve decided to feed the
signals from his pots into two 4-channel 12-bit ADC breakout boards from
Adafruit (https://bit.ly/3w8xYt3). The
Teensy LC communicates with these
boards using a 2-wire I 2 C interface,
which means he devotes only two pins
to reading the signals from all six pots.
However, there is a price to pay with
respect to the time overhead associated
with using the I2C.
To understand just how much overhead we’re talking about, Steve created
a simple test program (file CB-May2205.txt) to compare the times (in microseconds) it takes to read six pots one
time and ten times; also, to perform
these reads directly from an analogue
input and then via an I 2 C breakout
board. Just for giggles and grins, I used
Steve’s program to test my Teensy 3.6.
The results from both processors are
shown in Fig.12.
Not surprisingly, considering their
relative clock speeds, the Teensy 3.6
performs the direct reads faster than
the Teensy LC, but the I2C reads take
about the same amount of time (actually, the Teensy 3.6 is a tad slower with
respect to the I2C reads, but I have no
clue why this should be).
Fig.13. Reading the pots 10x times with a rolling average.
Rolling along
So, our conundrum is that we want to
increase the number of samples, but we
don’t want to accept the hit in terms
of time. Happily, there is a solution to
our conundrum, which is to maintain
a rolling average (also known as a running average or a moving average). A
rolling average is commonly used with
time series data to smooth out shortterm fluctuations and highlight longerterm trends or cycles. Once again, this
is a simple type of FIR filter.
In this case, we commence by setting all of our values to 0. Each time
around our loop, we take only a single
sample from each pot. The trick is that
we store the past ‘n’ samples. Whenever we are ready to check the results,
we sum these ‘n’ samples and divide
the result by ‘n’ (file CB-May22-06.txt).
The results of a rolling average using
a sample size of 10 are shown in Fig.13.
Observe how – since we start by initialising all of the sample values to 0 –
the results gradually increase over the
course of the first 10 iterations around
the loop, after which all of the values
remain rocksteady.
It’s all meaningless
As I mentioned earlier, the small amount
of wobble we were seeing prior to our
rolling average solution isn’t realistically of any import with respect to our
animatronic application, which essentially means that our wibbly wobbly
discussions above are meaningless in
this context (I also noted that the techniques discussed here may prove to be
of interest for other applications in the
future, so all is not lost).
Why do I say this? Well, let’s assume we
don’t do any frequency filtering and we
return to using our raw readings from Fig.8.
We introduced the concept of pulse-width
modulation (PWM) in an earlier column
(PE, March 2020). Suppose we wished to
use the 0 to 1,023 readings from our pots to
generate PWM signals to control LEDs, for
example, where these PWM signals have
a range of 0 to 255. This means we need
to map our 0 to 1,023 source values onto
corresponding 0 to 255 target values. In
this case, the easiest way to do this is to
divide our source values by 4 (which is
equivalent to shifting them right by two
bits). This essentially truncates the two
LSBs, which is a form of amplitude modulation that discards the wibbly wobbly
portion of our signals.
When it comes to the hobby servos we
are using to control our animatronic noggins, we don’t want any wibble wobble
on the signals we read from our pots to be
translated into jittery twitches on the head
and its eyes. So, let’s think this through.
Although they are capable of a greater
range of movement, we are currently rotating our servos through a range of only
approximately –45° to +45°. Even assuming an accuracy of 0.5°, which I think is
being generous, this means that I will be
mapping the 0 to 1,023 values from my
pots into the equivalent of 0 to 179 values
used to drive my servos, which means I
won’t even see my two wibbly wobbly
LSBs. (Similarly, Steve will be mapping
the 0 to 4,095 values from his 12-bit ADCs
onto the same 0 to 179 values used to drive
his servos, which means he can discard
his four wibbly wobbly LSBs.)
As usual, we’ve only touched upon a
huge topic, but at least it gives us something to noodle on until we meet again.
Teensy LC Teensy 3.6
6 Standard Analog Reads
69
43
60 Standard Analog Reads
644
29 8
6 I2C Analog Reads
12, 055
12, 29 7
60 I2C Analog Reads
120, 538
123, 035
Fig.12. Results of analogue reads (in µs).
Practical Electronics | May | 2022
Cool bean Max Maxfield (Hawaiian shirt, on the right) is emperor
of all he surveys at CliveMaxfield.com – the go-to site for the
latest and greatest in technological geekdom.
Comments or questions? Email Max at: max<at>CliveMaxfield.com
53
|