This is only a preview of the January 2021 issue of Practical Electronics. You can view 0 of the 72 pages in the full issue. Articles in this series:
|
A
C lockw ise
B
Low- to- high
transition
A
better to measure the
pulse time period and
then use the formula
Freq = 1/(Time Period),
This is what we will
examine next by using
the PIN configuration
parameter instead.
Using PIN
To measure the cycle time
period, the Micromite
B
firmware just needs
to accurately measure
the time between two
Fig.3. The rotary encoder outputs two digital signals: ‘A’
successive low-to-high
and ‘B’. By detecting a low-to-high transition on ‘A’, we
transitions. By using
can read the logic level of ‘B’ to determine the direction
SETPIN 16, PIN in the
of rotation.
above program, we can see
a frequency count can be provided. Gatethis time period measurement in action.
time, therefore, determines how often the
Change the second line (with no
output result is updated (important if the
option parameter), and also set the
frequency of the data signal varies).
value of Freq to 50 (ie, 50Hz). On running
Now refer back to the syntax of the
the program, you will see the value 20
SETPIN command and you’ll see there
displayed, which means the period of
is an option parameter. An important
the 50Hz signal is 20ms. The result is
point here is that when you use the
always in ms – a value of 20 means 20ms
FIN configuration parameter, the
(0.02s). As a sense check, note that Freq
option parameter defines the gate time
= 1/(Time-Period) = 1/0.02 = 50Hz.
in milliseconds (ms). So why would we
When the configuration parameter
want to adjust the gate time? Well, if the
PIN is used with the SETPIN command,
frequency of the data signal is very high,
the option parameter can be used to
then you could count many pulses in
determine over how many pulse cycles
a shorter space of time and achieve an
the measurement is taken to average the
accurate result quicker. In this scenario,
period measurement. Valid values are 1
the output would be updated more often
(default) to 10000. You would tend to set
(shorter gate times mean the count result
this to a higher value when measuring the
is displayed sooner). Similarly, if the data
time period of higher frequency signals.
signal has a very low frequency, then a
To see this in action, set the Freq value
much longer gate time is required in order
to 5000 (ie, 5kHz), and run the program.
to count a number of pulse cycles in order
The resultant time period displayed is not
to measure the frequency. You couldn’t
really accurate, so now add the option
use a gate time of one second to measure a
parameter with a value of 1000 so that
signal that only changed every 10 seconds!
1000 pulse cycles are timed and averaged.
To see the above in practice, stop the
On running the program, you will now see
program (Ctrl-C), and then EDIT the
the value 0.2 displayed. This represents
program to set the Freq variable to 200000
a time period of 0.2ms = 200µS, which
(ie, 200kHz) – then RUN the program
is the period of a 5kHz signal.
again. We are still using a one second
In summary, when measuring highgate time, so there is still an observable
frequencies, it is better to use FIN, and
‘delay’ before the result is shown.
when measuring low-frequencies, it is
Next, shorten the gate time to 10ms by
better to use PIN.
changing the second line to SETPIN 16,
FIN, 10 and on running the program
Using CIN
you should see the resultant frequency
The configuration parameter CIN is
displayed much quicker (every 10ms).
used if you simply just want to count
In summary, when using the F I N
pulses (or to be precise, count low-toconfiguration parameter, ensure you
high transitions). On configuring a pin
use an appropriate gate time to allow
with CIN, an internal counter is reset to
MMBASIC to count a decent quantity
a value of zero. Then, on every low-toof pulse cycles (which is ultimately
high transition, the counter increments
determined by the frequency of the input
by one. Then, whenever you use PRINT
data signal). The gate time parameter
PIN(x) (where x is one of the four valid
value must be between 10 and 100,000;
COUNT pins), the value of the counter will
and the outputted value is always in
be displayed. To reset the counter back to
hertz, regardless of the gate-time value.
zero, simply use SETPIN x,CIN again.
When measuring signals with a
Note that the Micromite can detect input
frequency less than 10Hz, it is often
pulses as brief as 10ns, and hence if CIN
A nticlockw ise
52
is used, for example, to try and count
button presses on a push-button, then
any mechanical bounce as the button is
pushed will also be counted (which is why
it’s important to debounce mechanical
switches). Therefore, CIN is much more
suited to counting pulses in a true digital
signal as we will now explore. Note, there
is no option parameter when using CIN.
Using our existing code, set the Freq
value to 1000, ie 1000 pulses will be
generated every second. Then change the
second line to SETPIN 16, CIN and run
the program. You will see the pulses being
counted, with effectively the number of
‘thousands’ being the number of seconds
the program has been running for.
Have a play by changing the value
of Freq, and see how this affects the
displayed value after each second.
The above shows how to use the
Micromite to perform various counting
tasks on a digital signal. We will now look
at a slight variation to this in the form of
detecting pulses from a rotary encoder.
Rotary encoders
A rotary encoder is a rotary position
sensor, but it can also be used as a ‘digital
potentiometer’ which has no limitation on
its rotation – it can be continually rotated
in either direction. Instead of containing a
variable resistance, a rotary encoder simply
outputs a sequence of digital pulses, often
as two separate digital outputs. By knowing
how to interpret these pulses, we are able
to determine the direction (and speed) of
rotation – more on this shortly.
Rotary encoders come in many different
styles; however, we really like the one
shown in Fig.2. It has a built-in RGB LED
which can be made to illuminate through
the clear plastic shaft; and by pushing
down on the shaft, you can activate the
built in push-button. In addition, while
rotating the shaft, it has a soft ‘click action’
which provides nice tactile feedback. These
features are not all normally found on a
rotary encoder; and when you consider
that it is readily available online at low
cost, you can see why it is our favourite
rotary encoder. To make it breadboard
friendly, an optional breakout-board is
also available (see Fig.2).
Decoding the pulses
The pulses generated by this rotary encoder
are output on two digital signal lines –
labelled ‘A’ and ‘B’ on the breakout board.
These pulses are actually generating a
2-bit Grey-code signal. We won’t explain
the details of Grey code here, but Fig.3
shows the kind of signals it creates. The
point to observe here is that there are
two possible rotations – you can turn it
clockwise, or anti-clockwise. So how do
we decode these pulses? The answer is
actually quite simple once you apply the
Practical Electronics | January | 2021
PULLUP option is used
to tie the default logiclevel high (with the
A C B
Eq uiva lent circuit
rotary encoder simply
3.3V
pulling it low whenever
it needs to output a low
R ed
Green
B lue
pulse). The second line
NC
R 1
R 2
configures pin 18 as an
470Ω
470Ω
input so that the logic
level on signal ‘B’ can
22
24
21
be read when required.
+
B SW G R
The third line sets a
R 1
470Ω
NC
variable that we have
22
3.3V
named Rot_Value with
a value of 50 – it also
24
R 2
prints this value on the
21
470Ω
terminal screen.
A simple DO…LOOP is
Fig.4. The rotary encoder connects to the MKC with three
included, and acts as the
connections to read the output pulses. The Digital Safe project
main program. It does
adds connections for the RGB LED and the push-button.
not do anything here,
but is required so that the program can
continue to run while waiting for a lowfollowing technique. Referring to Fig.3,
to-high transition on pin 17 (ie, from the
consider the moment in time when there
rotary encoder’s signal A output.
is a low-to-high transition in signal A. If
The interrupt subroutine is the part that
signal B is at a low logic level (highlighted
then determines the direction of travel
by the blue circle), then the shaft is rotating
by reading the state of pin 18. Depending
clockwise. However, if signal B is at a
on the state of pin 18, Rot_Value is
high logic level (highlighted by the red
either incremented by 1 (clockwise),
circle), then the shaft is rotating in an
or decremented by 1 (anticlockwise).
anti-clockwise direction. It’s that simple!
And before the subroutine is exited, the
Note that you could detect the transition
new value of Rot_Value is displayed
of signal B instead, and then read the
on the screen. Note that the PAUSE
logic level of signal A to determine the
command adds a small delay to remove
direction. And you can also use a highany mechanical contact bounce generated
to-low transition – whatever option you
by the rotary encoder.
select, just stick with it.
RUN the program to ensure it works
Let’s put this into practice with a few
correctly by spinning the rotary encoder.
lines of code. First, refer to Fig.4 for the
Upon each ‘click’, you should see the
circuit diagram. Note at this stage we only
value displayed on the screen increase
need to connect the three contacts labelled
or decrease according to the direction
‘A’, ‘B’, and ‘C’ to the MKC (respectively
of rotation.
to pins 17,18 and 19). A and B are the two
If you see the above work, but ‘in
signal lines, and C is effectively a common
reverse’ (ie, increase with an antithat is connected to 0V. Connect this part
clockwise rotation), then you can either
of the circuit, and then enter the following
make a hardware change (by swapping
short program:
the connections to pins 17 and 18), or you
can change the code inside the interrupt
SETPIN 17, INTH, MyInt, PULLUP
subroutine – I will leave it to you to work
SETPIN 18, DIN, PULLUP
out what to change!
Rot_Value=50 : PRINT Rot_Value
17
0V
18
DO : PAUSE 1 : LOOP
SUB MyInt
PAUSE 0.1
IF PIN(18)=0 THEN
Rot_Value = Rot_Value + 1
ELSE
Rot_Value = Rot_Value - 1
END IF
PRINT Rot_VALUE
END SUB
The first line of code simply configures
pin 17 to trigger an interrupt subroutine
(called MyInt) whenever a low-to-high
transition is detected on signal ‘A’. The
Practical Electronics | January | 2021
Digital safe
Having seen how to use a rotary encoder
to increase and/or decrease the value of a
variable depending on which direction it
is ‘spun’, it is now time to have some fun
by demonstrating how a rotary encoder
can be put to good use in a practical
project – we will simulate entering a
safe’s combination-lock number in a
short demo program. This will require
the use of the red and green LEDs built
into the rotary encoder, as well as the
built-in push-button.
Now connect the rest of the circuit
shown in Fig.4 (ie, connect the MKC to the
push-button SW contact, and LEDs R and
G via 470Ω resistors). Next, download and
RUN the DigitalSafe.txt program (available
from the January 2021 page of the PE
website). On running the program, you
will see the current ‘combination dial’
value displayed on the terminal screen.
Simply turn the rotary encoder in the
appropriate direction to enter the three
required values of the combination: 3,
46, 22. When you reach the first required
value, push the encoder shaft to activate
the push-button, which in turn ‘submits’
the number displayed on the terminal
screen. Continue with the second and
third required values above in a similar
manner. If you entered the three-number
combination correctly, then the green
LED will illuminate, otherwise the red
LED will illuminate, meaning you failed
to open the safe!
The code is commented throughout
so we won’t go into the details here,
but do take the time to look through the
code to see how easy it is to create this
‘digital safe’.
Challenges
Once again, there are many things you
can change in the program code to affect
the way it works. In this example, why
not add hardware too – here are some
challenges:
1. Increase the range of each value from
between 1-50 to between 1-99 (or greater)
2. Make the safe more secure by increasing
the length of the combination number
from three values to five values (or more)
3. Add a time-out feature; ie, the
combination has to be entered within
a certain amount of time
4. Add a piezo sounder to give audible
feedback to signify a correct combination
entry, and a different sound if incorrect
5. Add a relay and a solenoid to complete
the lock!
Next month
We have covered a wide range of topics
throughout the series, and along the way
encouraged you to experiment and build
your own Micromite-based projects.
Several of you have written in to ask if
there are more powerful versions of the
Micromite. For example, devices that can
run faster, or have more memory, or have
additional features and commands for
controlling different hardware, such as
SD cards for storing data, or for driving
larger displays with higher resolutions.
The answer to all of these is very much
yes, there are indeed different Micromites
available, as well as different versions
of MMBASIC. Next month, we will
provide a summary overview of what
else is available for those of you wanting
to advance beyond the power of the
Micromite Keyring Computer.
Until then, have fun coding!
53
Circuit Surgery
Regular clinic by Ian Bell
Interference and noise
R
ecently, Michael Lamontagne posted a question
on the EEWeb forum concerning a possible ground loop
problem when measuring an op amp circuit with an oscilloscope. Rather than looking at this specific case in detail (partly
because we are not certain enough about exactly how everything
was wired up) we will take a quick look at unwanted signals in
general, specifically noise and interference.
Noise and interference
Unwanted signals present in electronic systems get often referred to
as ‘noise’, although we can be more precise with our terminology.
In audio system it may make its present felt as hiss, hum, buzzes
and crackles. In sensor systems, it limits measurement of low-level
signals and degrades accuracy of measurement. Noise may already
be present as part of an input signal (eg, it may come from a sensor
along with the wanted sensor signal), or it may be introduced by
the circuitry (eg, amplifier) used to process the signal. For example,
all resistors generate random electrical noise – you cannot prevent
this, it is part of their basic physics. Circuits also produce nonrandom unwanted changes to signals – distortion, which we will
not be looking at in this article. Unwanted signals may also come
from outside or elsewhere in the system, coupled or picked up
inadvertently and added to the signal being processed – this is
often called ‘interference’ to distinguish it from random noise.
Crosstalk is interference between multiple channels or signal paths.
Random noise
Radom noise causes the instantaneous value of a signal to
deviate from its ‘true’ value, with decreasing probability for
larger deviations. The specific mathematical probability function
depends on the type of noise, but may be the well-known Gaussian
or normal distribution, familiar to all statisticians. There are a
variety of types of random noise generated within electronic
circuitry; these include thermal noise, shot noise, flicker noise,
and avalanche noise. This noise generated is fundamentally due
to the discrete nature of electricity at the atomic level – electric
charge in circuits is carried in packets of fixed size (eg, electrons).
The waveform in Fig.1 shows a random voltage variation with
time. This gives us some simple insight into what noise ‘looks’
Fig.1. Random signal (noise).
54
like, but in general, plotting random noisy signals against time
is not particularly useful. When dealing with noise we often
need to look at the spectrum of the signal – the variation of
signal level against frequency.
Unwanted signals may look like random noise (eg, on an
oscilloscope), but they can actually have significantly different
characteristics. For example, the noise on the power supply of
a digital circuit may look random, but a look at the spectrum
will show that certain frequencies, related to the system clocks
will be dominant. Pure random noise has a smooth continuous
spectrum – for example, that shown in Fig.2.
Random noise may be classed according to the shape of its
spectrum. White noise has the same power throughout the
frequency (f) spectrum, whereas 1/f noise (or pink noise) decreases
in proportion to frequency. For 1/f noise there is the same amount
of noise power in the bandwidth of say 100Hz to 1kHz, as there
is in 1kHz to 10kHz, whereas for white noise there would be 10
times as much power in the bandwidth 1kHz to 10kHz as 100 to
1kHz because it is 10-times larger. Amplifiers (and other circuits)
typically exhibit a mixture of pink and white noise, with pink
noise dominating at low frequencies. The frequency at which
the dominant noise component changes between pink and white
noise is called the corner frequency or noise corner (see Fig.2).
The fact that the components in any electronic circuit or system
generate random noise means that there is always a certain level
of noise, even with no signal present. This is known as the noise
floor, which is important because the circuit cannot meaningfully
process input signals that are smaller than the noise floor. As noise
floor relates to noise within the circuit, this is different from noise
within the input signal. If the properties of the required signal
are known then there are techniques which can extract signals
that are smaller than noise present within the signal.
The difference between the signal and the noise is often important;
it is expressed as the ‘signal to noise ratio’ (SNR), usually in
decibels (dB) and based on the ratio of noise power (hence the v2
terms in the equation). Larger values indicate better performance.
𝑣𝑣%&
𝑣𝑣%
𝑆𝑆𝑆𝑆𝑅𝑅!" = 10 𝑙𝑙𝑙𝑙𝑙𝑙#$ * & , = 20 𝑙𝑙𝑙𝑙𝑙𝑙#$ . /
𝑣𝑣'
𝑣𝑣'
Fig.2. Typical spectrum of amplifier noise.
Practical Electronics | January | 2021
points. Careful circuit design and construction
can greatly reduce these problems.
S ource of interf erence; eg, digital clock line
Capacitively coupled interference (see
Fig.3) can be reduced using screening, which
C ircuit 1
C ircuit 2
effectively grounds the interference coupling
capacitance. Screening is implemented using
a)
coaxial (screened) cable to link (for example) a
Ground
sensor to a circuit, and by enclosing the sensitive
circuits in a grounded screening box. The source
of interference can also be screened to reduce
A lternative connection
C ircuit 1 ground vi a screen;
its effect on other circuits. Choice of where the
usef ul f or ‘ f loating’ sensors
screened cable is grounded may have an effect
C ircuit 1
C ircuit 2
C ircuit 1
on circuit performance due to the possibility
S creened cab le
of creating grounding loops if the screen/signal
return path is grounded at both ends (more on
b)
Ground
this a little later). For differential signals, we can
also use screened wires – the two signal wires
form a twisted pair and are enclosed by the screen
Fig.3. Capacitively coupled interference.
(see Fig.4). Here, grounding at both ends is less
of a potential problem as the ground does not carry the signal.
Magnetic interference is worse when physically large loops
Here, vs is the rms signal voltage and vn is the rms noise voltage.
occur in the circuit (see Fig.5) but can be reduced by avoiding
When using or quoting SNR values, the bandwidth (range of
such loops – for cables, use of twisted pairs of wires is an effective
signal and noise frequencies considered) should be quoted
approach. For PCBs, use a ‘ground plane’ on one side of the
because noise power is frequency dependent and noise may be
board and for ribbon cables each signal can be given an adjacent
present well outside the range of signal frequencies of interest.
ground wire. Circuits can be shielded against magnetic fields,
but this is not used as commonly as shielding for capacitive
Interference
coupling as it requires special high-permeability materials such
External signals may get into your circuit through electrostatic,
as Mu-Metal. These materials are expensive and since they may
electromagnetic and magnetic coupling. In electrostatic coupling,
need to be quite thick the screening may be bulky.
a high-impedance part of your circuit acts like one plate of a
Power supplies can be a significant source of unwanted
capacitor; in magnetic coupling, a loop in your circuit acts like
signals. The circuit in Fig.6 illustrates how supply resistance
the secondary of a transformer; and in electromagnetic coupling,
leads to errors or interference. The supply current taken by
parts of your circuit act like antennas. Mains hum signals (at
a circuit causes a voltage drop across the supply wiring; so,
50/60Hz) and radio frequency interference from other electronic
for example, the ‘ground’ voltage at each subcircuit will not
systems such as phones and computers are obvious examples
actually be the same (as measured from the same reference
of external interference. The amount of external noise a circuit
point). Fig.6 is a simplification – every branch of the supply
is subject to will vary greatly depending on its location. The
wiring will have resistance and hence cause voltage drops.
problem will tend to be worse close to things like power lines,
Supply and group voltage drops may cause problems if we are
electrical machines and transmitters such as mobile phones.
trying to accurately process voltage signals. If the supply currents
Signals in one part of your circuit can find their way into other
are constant, then the error will be an offset (DC error) but the
parts of the circuit where they cause problems. A common example
ground voltage is not necessarily constant; as the supply current
of this is the clock of a digital section of a mixed analogue and
of one subcircuit varies then the supply voltage drop and hence
digital circuit getting into an analogue section, via the power
the error voltage at this and other subcircuits fluctuates (this is
supply lines or by capacitive coupling to high-impedance
sometimes called ‘ground bounce’). This problem can be very
significant, for example, when one subcircuit has a digital clock
C ircuit 2
signal that is coupled via the supply into a sensitive amplifier.
This situation can also occur in the mains wiring – along the
C ircuit 1
equipment power cables and the wiring between supply outlets.
S creened C ab le
A solution to supply and ground noise is to wire connections
Ground
separately to a single point rather than using the same pointto-point wire for all the connections (see Fig.7). This approach
applies equally to the wiring inside the cabinet of an instrument
Fig.4. Screened differential signal.
and to the supply connections on an integrated circuit. It may
be more difficult to achieve with mains wiring, as it cannot be
easily changed and doing so may be very dangerous.
C ircuit 1
Magnetic f ield
C ircuit 2
Rsupply2
Rsupply1
S upply
C ircuit 1
C ircuit 1
C ircuit 2
C ircuit 2
Rground1
Fig.5. Large wiring loops (upper schematic) make a circuit
susceptible to voltages generated by magnetic fields. Reducing loop
size (lower schematic) helps combat the problem.
Practical Electronics | January | 2021
Rground2
S upply
Fig.6. Supply wiring resistance causes voltage shifts and noise due
to supply currents.
55
|