This is only a preview of the May 2020 issue of Practical Electronics. You can view 0 of the 80 pages in the full issue. Articles in this series:
|
PIC n’Mix
Mike Hibbett’s column for PIC project enlightenment and related topics
Audio Spectrum Analyser – bandwidth expansion
I
t’s a bumper issue this month
as we complete our Audio Spectrum
Analyser project.
The circuit is based around a dsPIC33
DSP (digital signal processing) microcontroller and a low-cost 320 × 240 colour
LCD display sourced from eBay.
The software has been developed using
Microchip’s free FFT (fast Fourier transform) library, and Adafruit’s free graphics
library that was compatible with our display. Those libraries provided the complex
software, leaving us with figuring out how
to use and modify them to work with our
processor of choice, and our schematic.
Nowadays, for the many projects that make
use of freely available pre-existing source
code, that modification work is the hard
part. Once done, adding new features like
changing the operation of the system in
response to a keypress or drawing cool
logos is a relatively simple task, fun to
do and highly rewarding.
We complete the project this month
by adding functionality to the buttons,
testing out the new LDO voltage regulator, and building a 3D-printed enclosure.
Display recycling
The first step was to salvage the LCD
display from the PCB assembly of the
previous design; we had only purchased
one LCD module and it would take weeks
for a new one to arrive from eBay. Separating the boards was done by cutting
each pin from the two headers binding
the PCBs together. The next step was to
remove the pins one by one from the LCD
module with the aid of a soldering iron
and then cleaning up the holes for fitting
new a new header strip. When cutting
off header pins, leave enough length on
the pins in the LCD module so that you
can easily pull on them with pliers. Once
done and with the plastic spacer carefully
cut away, each hole was cleaned up with
solder wick to allow a new 0.1-inch strip
of header pins to be inserted. The original
PCB was discarded. We could have salvaged the processor, but at a cost of just a
few pounds, we did not want to take the
risk of building a circuit using an IC with
heat or mechanical damage. True enough,
with care, removal is possible, and you
may find it an interesting desoldering
challenge! We, however, were on a tight
timescale, so the board was discarded.
(We did salvage the electret microphone,
a simple two-lead device – plus, it was
the only one we had. Removal is a simple
job of heating both leads simultaneously.
This could be done quickly with a low
risk of damaging the part.)
New PCB
Now we can start to populate the new PCB.
First though, let’s look at the PCB under
the microscope to see the manufacturing
quality. As you can see in Fig.1, the alignment of the key manufacturing processes
is excellent. The drill holes are very well
centred in the pads, and the solder resist
layer – which is very important to help
prevent solder bridges between component pads – is both well aligned around
the pads, and also hugs very close to each
pad – maximising the amount of this protective layer that is available. This is a
very good job by PCBWay.
Choose your PSU
Fig.1. New PCB, close up. The solder mask
and drill alignment to the copper are excellent.
48
A key point to note in the schematic,
shown in Fig.2, is that we now allow for
two power supply choices – if you build
this circuit, populate only one! The choice
is based around IC1, a switching regulator that has a wide input voltage range,
and IC3, a simple linear regulator. We
discussed the pros and cons of each in
the previous article; this month, we are
populating the linear regulator version,
as it offers the lowest noise into the rest
of the circuit (the original PCB used the
switching regulator, and we were disappointed by the additional noise, although
it did not appear to limit performance.)
The linear regulator circuit takes an
input of 3.3V to 6V – ideal for four AA
batteries – so we will power the circuit
from this supply. We will also validate on
a bench power supply what the current
consumption is across that voltage range,
so we can get an expectation of the battery
life. The inclusion of an on-off switch in
the enclosure design will ensure that we
prolong battery life as long as possible.
Returning to FFTs
We start our design upgrade by considering the more complex requirement, which
affects both hardware and software change
– moving from a maximum input signal
of 1kHz to a maximum of 20kHz, covering the full human hearing range.
Let’s recap on our hardware design, as
that limits some of our design choices.
First, our spectrum analyser display is
fixed at 256 data points, as we only have
256 horizontal pixels to play with. There
is no point adding more data points; we
cannot display them. Using extra data
points would mean having to average
those extra data points into one – which
is no better that simply using a lower
FFT size. So, a 256-point FFT remains
our design specification.
What we are changing, however, is
the sample frequency, the rate at which
we perform an analogue-to-digital conversion on the input signal. Previously,
we used a sample rate of 2kHz, giving us
the ability to display signals up to 1kHz.
We would like to improve the design to
be able to display signals up to 20kHz
(now way beyond your author’s hearing
range,) which will require us to increase
the rate at which we perform analogue-todigital conversions from 2kHz to 40kHz.
That is well within the capabilities of the
dsPIC33’s ADC peripheral and should
pose no problem to our application, as
it does nothing else while collecting
ADC samples.
Practical Electronics | May | 2020
PIC n’ Mix files
I C3
MCP 17 00T -3302E/ T T
3
C14
10µ F
X 5R
10V
3. 3V – 6 V inp ut
regulated P S U
VIN
1
VOUT
2
The programming files discussed
in this article are available for
download from the PE website.
C15
10µ F
X 5R
10V
GN D
A nalogue p ower sup p ly f ilter
1. 5V – 5. 5V inp ut
regulated P S U
B attery
B attery+
2
B attery–
1
JP
I C1
T P S 6 109 7 A -33DB VT
3. 3V
5
A _ 3. 3V
L1
S RN 3010T A -100M
1
5
C1
100nF
3
C2
10µ F
X 5R
10V
2
L
VOUT
R6
0Ω
VIN
EN
C4
100nF
GN D
C3
10µ F
X 5R
10V
k
C12
0F
(op en
circuit)
S D med ia
R5
10kΩ
C13
0F
(op en
circuit)
C5
10µ F
X 5R
10V
4
Mic
1
3
2
R4
2.2 Ω
1
JP 2
N o connections
used f or
mech anical
sup p ort only
P I Cki t 3
H ead er
6
5
4
3
2
8
R1
. kΩ
1
MCLR
2
3. 3V
3
GN D
4
P GD
5
P GC
6
7
1
JP
PJ
1
JP
1
R3
. kΩ
8
3
9
10
11
12
13
14
C8
100nF
R2
. kΩ
I C2
d sP I C33EP 256 GP 502-I / S O
MCLR
A VDD
A N 0/ O A 2O UT / RA 0
A VSS
A N 1/ C2I N 1+ / RA 1
RP I 4 7 / T 5CK / RB 15
P GED3/ VREF– / A N 2/ C2I N 1-/ S S 1/ RP I 32/ CT ED2/ RB 0
RP I 4 6 / T 3CK / RB 14
P GEC3/ VREF+/ A N 3/ O A 1O UT / RP I 33/ CT ED1/ RB 1
RP I 4 5/ CT P LS / RB 13
P GEC1/ A N 4 / C1I N 1+ / RP I 34 / RB 2
RP I 4 4 / RB 12
P GED1/ A N 5/ C1I N 1-/ RP 35/ RB 3
T DI / RP 4 3/ RB 11
VSS
T DO / RP 4 2/ RB 10
O S C1/ CLK I / RA 2
VCAP
O S C2/ CLK O / RA 3
VSS
MS / A S DA 1/ S DI 1/ RP 4 1/ RB 9
RP 36 / RB 4
CVREF2O/ RP 20/ T 1CK / RA 4
VDD
T CK / CVREF1O/ A S CL1/ S DO 1/ RP 4 0/ T 4 CK / RB 8
S CK 1/ RP 39 / I N T 0/ RB 7
P GED2/ A S DA 2/ RP 37 / RB 5
P GEC2/ A S CL2/ RP 38 / RB 6
MI C+
2
C10
3. 6 p F
28
VCC
LED
C11
10µ F
X 5R
10V
C7
100nF
MI C–
4
27
26
4
25
3
24
9
23
5
22
6
21
7
20
C6
10µ F
X 5R
10V
19
18
CS
S DO
D/ C
S DI
10
12
13
17
11
16
14
S CK
T -CLK
T _ DI N
T _ DO
T _ CS
T _ I RQ
15
2
C9
100nF
RES ET
GN D
LCD p anel
S 2
S 1
This is a very simple change in the
software. Just two lines of code change,
as shown below:
#define SAMPLE_RATE 2000
Changes to:
#define SAMPLE_RATE 40000
And for the ADC peripheral:
PR1 = 32200;
Changes to:
PR1 = 1610;
Signal input
Now let’s look at the hardware changes
required to support this higher input
frequency. The input circuit from the
microphone to the ADC of the processor
includes an amplifier, which is buried
within the microcontroller itself, and so
Practical Electronics | May | 2020
the detail is not obvious from the schematic in Fig.2. The key point is that the
amplifier includes two external components, a resistor and a capacitor (R4 and
C10 on the schematic) which will provide some low-pass filtering as well as
setting the gain of the amplifier. Filtering
out higher frequency signals is desirable
as these can appear as phantom signals
at lower frequencies, through a process
called aliasing. It’s complicated, but
the key point is to filter out unwanted
higher frequency signals, otherwise they
will interfere.
We will build the circuit up slowly so
we can first test the microphone sensitivity, and to get a good understanding
of the amount of gain we will need to set
in the amplifier. We are going to do this
empirically (ie, by guessing component
values and measuring the results) rather
Fig.2. Updated
circuit schematic.
than through simulation, as we have no
information on the microphone to model
its characteristics.
We start by assembling the voltage
regulator circuit based around IC3, R6
(using a zero-ohm link or very low value
resistor), C14 and C15. Then we add the
microphone circuit consisting of R5, set
to a value of 10kΩ. C5 was not connected,
as we want to test the microphone circuit
and op amp circuits independently.
To help with these measurements we
purchased an AFG (arbitrary function generator), the ISO-TECH AFG-21012 on eBay.
At £150 it’s a serious investment, but very
useful for projects like these where you
would like to see the true performance of
a circuit when presented with AC signals.
An arbitrary function generator has many
other uses too, so it’s a welcome addition
to the lab. You can see our setup in Fig.3.
49
Fig.3. AFG – our brand new Arbitrary
Function Generator.
We connected the AFG to a small loudspeaker and generated a 1kHz tone, placing
the loudspeaker next to the microphone.
Powering up the circuit – remember, the
microphone requires power – we discovered that the microphone has an output
that varies in amplitude from 5mV to
150mVpk-pk (peak to peak) when the sound
varies from quiet to loud.
We now know the amplification that we
want to achieve; from 5mV – 150mVpk-pk
up to 3Vpk-pk, a gain of between 20 and 600.
It’s time to wire up the op amp and experiment with setting the gain. To do that, we
must wire up the processor sub-system
and load the original application, as the
op amp must be configured by software.
So, we assemble the remaining circuit.
The microphone amplifier circuit based
around R4, C10, and the op amp built into
the microcontroller can be viewed as the
circuit shown in Fig.4. This is (loosely) an
inverting amplifier, gain controlled by R4,
with a low-pass filter determined by R4
and C10. The gain is the ratio of R4/Rin;
we didn’t include a resistor in the input
circuit, relying on the impedance of the
microphone. This drove a bit of trial and
error to find values for R4, and we settled
on 2.2MΩ, a gain of approximately 220.
That’s quite a large value resistor, but it
made the device nicely sensitive to ambient level sounds. You can go higher, but
the device quickly becomes too sensitive
and can be easily overloaded, clipping
the audio signal and generating misleading harmonics on the display. 2.2MΩ
works really well. We implemented some
low-pass filtering by adding C10 with a
value of 3.6pF, giving a cut-off frequency
at approximately 20kHz. This will not be
a very effective low-pass filter, but it will
remove some of the higher frequency signals (such as oscillator and SPI bus noise
from the board itself) being aliased into
the displayed frequency range. Improving this circuit with a switchable op amp
filter would have improved the quality of
the displayed signal, but that can be considered a future improvement.
Why is attenuation for higher frequencies important? Having higher frequency
signals present at the input to the ADC
will result in aliasing – those higher frequency signals appearing to be lower in
frequency and will end up being displayed
on the LCD. You can see this effect in
Fig.5. Filtering these out or minimising
them greatly before they reach the ADC
will stop them generating ‘fake’ signals
on your display.
It was interesting playing with the
sound generated by the AFG, especially
as the frequency is raised out of hearing
range, but with the spectrum analyser still
faithfully displaying the signal. For the
author, a quiet sound level stopped being
audible at around 8kHz, but the signal was
of course still visible on the display. Raising the frequency above 12kHz resulted
in the displayed signal dropping to zero,
probably as a result of the loudspeaker
and microphone limitations, as these are
not high-fidelity devices. Increasing the
signal level output from the AFG saw the
signal reappear, right up to 20kHz.
We’ve released a YouTube video demonstrating this effect, which can be viewed
here: https://youtu.be/mGIGxUU9w1k
Software
First, we replaced the old EPE logo with
the new PE one. We wrote a simple Python
script to convert the magazine’s logo to a
data file suitable for including in the program. The source code for this is provided
in the project download file, should you be
interested in changing any of the graphics.
Next, we moved onto the more challenging software task – adding a user
interface to the device, enabling the buttons to change the behaviour of the device.
Unused
I nsid e th e d sP I C
p rocessor
Fig.4. Microphone pre-amplifier circuit.
T h is lower f req uency signal would be d isp layed in error
Fig.5. Aliasing – we need to filter out high
frequencies that can give erroneous data.
S p ectrum
d isp lay
200
O utp ut
+
50
Logo
24 0
–
T itle
8 5
R4
RI N
26 0
H igh er f req uencies can generate d ata
p oints th at mimic lower f req uencies
C10
I np ut
In the previous article we gave the following desired functionality for the buttons:
Button A – On each press of the button,
cycle between peak frequency display,
peak trace hold, none. When active, the
peak frequency will be displayed in the
format nn.n Hz directly above the peak
signal.
Button B – On pressing once, the display will show the frequency span for
three seconds. On pressing the button
again while the span is being displayed,
the device will cycle through different
span settings.
Those are good and clear requirements,
but now we come to implement these requirements, looking at the display layout
(as shown in Fig.6) we realised that there
is a lot of available screen space unused
in the lower left of the display. The width
of this spare screen space is 60 pixels,
enough to display ten characters in a 5×7
font. There is space for eighteen rows of
characters, so there is plenty of room to
display useful information continuously,
irrespective of button presses. Doing so
will also simplify our software design, so
we chose to take this route.
The original Adafruit LCD driver software provided a simple 5×7 pixel character
font, so we made use of that. We imported
two functions from the original display
driver, ‘draw pixel’ and ‘draw character’. It took an hour to adjust the Adafruit
code to suit the Microchip development
environment, at which point we were
successful at displaying text – but on its
side. The Adafruit driver software expects
the display to be driven in portrait mode,
not landscape as we are using. No problem, back to hacking code. This driver is
going to become somewhat specialised
to our application.
The next step was to construct a ‘draw
string’ function, to display the ‘Peak’
and ‘Span’ text, and the values calculated on each display update. The draw
string routine was easy to implement,
and then converting the calculated values
into displayable strings was done using
a standard ‘C’ function, sprintf(). No
work required there.
Placing this text on the display revealed
an issue – for the author at least – the text
320
Fig.6. Mapping out our LCD real estate.
Practical Electronics | May | 2020
Handling button presses is
often a tricky part of a project’s
P O W ER
T I MER1
A DC
software design; there is no uniO N
IN T
IN T
versal ‘one solution fits all’, and
custom designs invariably involve interrupts and timers,
Conf igure
S tart an A DC
S tore A DC
LCD
conve rsion
samp le
which can be difficult to set up
and debug.
Let’s start our design by
Conf igure
B utton
remembering
what our requireA DC and buttons
ch ange
IN T
ments are, and understanding
what capabilities we have availEnable
able on the processor. When
interrup ts
H O LD
S
P
A
N
W h ich
a button’s state changes from
button?
‘not pressed’ to ‘pressed’, deS tart
S tart
bounce the press, then perform
W ait f or 512
T imer2
T imer3
A DC samp les
the action.
Here we are looking for interT I MER2
YES
IN T
rupt
capability on the pins that
H old ?
we are using as button input,
PORTB pin 5, and PORT B pin
T oggle
Comp uter
6. Fortunately, the processor
H O LD
FFT
provides a ‘change notification’
interrupt for all GPIO pins, so
we have the ability to detect
Red raw
T I MER3
LCD
IN T
button press and button release.
Once a button press is detected we need to wait for a
Disp lay p eak
Cycle th rough
f req uency
short time, typically 30-50ms,
S P A N settings
and re-check the input to see if
the button is still pressed. If it
is, perform whatever action is
Fig.7. The final application flowchart. The parts in the
required. We will use a timer
dash line boxes are the additions for handling the
to provide the delay, to avoid
button presses.
tying the processor up during
those 30-50ms. When the timer expires,
was too small to read without glasses.
it will jump to an interrupt routine that
Fortunately, the Adafruit graphics library
will perform the desired action, if it finds
for printing characters has a ‘double size’
that the button is still pressed. To simplify
option, scaling the font to 10×14 pixels.
the software, we will use two timers, one
This limited us to five characters across
for each button. The processor has five
the display, but the text is very clear. We
timers internally, so it’s not a waste of
can accommodate a width of five characlimited resources. You can see in the apters in the design by cunning selection of
plication flowchart in Fig.7 that the flow
display formatting.
of execution is very simple. The code for
Next, how to handle the buttons. As
this is actually quite simple; the complex
the program is a simple continuous loop,
part was finding out how to configure
shown in Fig.7, we could have detected the
the timer, and what names are used by
button press within the loop. Two issues
the compiler for the interrupt routines.
cause us to avoid this: at the lower ‘span’
Thankfully, these details are very, very
frequency settings, the processor will
similar between the different families of
spend a long time taking ADC samples so
microcontrollers, so this task took just a
we cannot rely on the amount of time the
couple of hours.
loop takes; button press responses will be
We took the opportunity to add severdelayed. We also need to de-bounce the
al different sample rates, with the SPAN
button press actions, which will require
button cycling between them. Providing a
checking the button level 30 to 50ms after
range of sample rates yields a significant
it has been pressed – this will slow down
benefit to the design. The FFT algorithm
the display update. So, we take the more
is fixed at 512 ‘bins’, providing 256 data
complicated route, and use an interrupt
points. At a 40kHz sample rate, which
routine to detect when the buttons have
equates to a maximum displayed frebeen pressed or released, and a timer to
quency of 20kHz, the resolution of the
trigger an action 30 to 50ms later to see if
display is 78Hz. This means that two
the button is still in the same state. This
signals close in frequency to each other,
way we can react very quickly to key presssay a 50Hz and a 60Hz signal, would be
es and be more efficient with the use of
lumped into the same vertical line. Prothe processor, allowing it to concentrate
viding a range of spans down to 500Hz
on reading ADC values, computing the
means we can come down to a resolution
FFT, and displaying it.
Practical Electronics | May | 2020
of 2Hz – which means those two signals
will be clearly visible across the display.
The only impact of doing this (there is
always a cost!) is what is referred to as
temporal resolution – at 500Hz the signal
acquisition takes a long time, 256ms. It
would be easy to reduce the peak frequency even lower to get a more accurate
reading on lower frequency signals, but
at each halving of the peak frequency, the
sample time doubles. For some applications this is perfectly acceptable, and it
is a simple change in the software if you
would like to test it.
We also decided to display the word
‘HOLD’ when the HOLD button has been
pressed, just for fun. It only added three
lines of code.
With these changes completed, the
software took just 23% of available code
space on the processor, leaving over 64KB
for future additions. You can see the finished project in Fig.8.
After testing it for a few minutes and
then correcting two small software bugs,
we removed the batteries and connected
a bench power supply. We observed a
continuous current draw of 120mA at 4V,
and that the circuit continued to function down to 2.9V (at room temperature,
at least.) Based on this, we decided to
use just three AA batteries to power the
project, which should provide 25 hours
continuous use.
3D printed enclosure
We’ve been using a 3D printer in the PIC
n’ Mix lab for ten years now, since we first
introduced the technology in February
2010. Then, 3D printers were an expensive novelty. Now, they have reduced in
price from £1200 machines to £160 (the
cost of the author’s current machine, a
Creality Ender 3 – a printer we cannot
praise enough.) By now, as hobbyists, we
either own a 3D printer or know people
who do and who are willing to print objects for us. From now on, expect to see
3D-printable enclosure designs for our
projects, where appropriate.
We will leave the detail of designing a
3D-printed enclosure to another series of
Fig.8. The finished project, in its 3D-printed
presentation case.
51
provide mounting points to the enclosure. We’ve seen
both employed on complex products, but for this device
the design is simple enough – four mounting posts, two
buttons and a hole for the LCD – that we have decided
to try the former approach. This reduces the number
of 3D printed components required from three down
to two, so it will be quicker and cheaper to build –
on a hobbyist printer this will be very cheap, under a
pound’s worth of plastic filament.
For this project, we took a different approach, choosing to make a holder for the assembly, leaving the
components exposed and clearly visible. We took this
approach because we wanted to display the project at
a Maker Faire, and it’s more interesting to be able to see
what’s going on. You can see our design in Fig.9, created
with the free design tool RS Design Spark Mechanical.
Fig.9. Enclosure design (fft-case.stl file available for download from the May
2020 page of the PE website).
articles, but the key point is that today, our recommendation is
to use RS Components Design Spark Mechanical software for
creating a design. The main reason is that this is an excellent application, easy to use and with many tutorials available online.
There are better design applications available, both free and paid
for (FreeCAD and Fusion 360 respectively) but for starting out in
3D CAD design with no previous experience, Design Spark Mechanical has, in our opinion, the best support for beginners. We’ve
been using it for a year and are still happy with the capabilities.
There are two common techniques employed when designing
enclosures for electronic products; design a two-part enclosure
that provides mounting points on one part for the electronics,
or design a ‘chassis’ for the electronics, and have that chassis
Final thoughts
While this Audio Spectrum Analyser is not a particularly ‘useful’ design, it’s certainly been very educational,
great fun to play with, and generated a lot of interest at
our local Maker Faire, as the LCD danced to music and voices.
With the inclusion of software libraries for graphics and text
display, it offers building blocks for other projects, even unrelated to audio. We are already planning a bedside alarm clock
for the version 2 hardware!
The software, PCB and 3D printer enclosure files are all available on the magazine website. The PCB can be ordered from
the PE PCB Service or directly from PCBWay, at this webpage:
http://bit.ly/pe-may20-pnm
This project has spanned two years, and we hope you have
enjoyed the journey and the results. If you take this design and
create something new, do tell us!
Need a programmed PIC for your
Practical Electronics project?
Coming soon from the Practical Electronics online shop at:
www.electronpublishing.com
52
Practical Electronics | May | 2020
|