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:
|
Make it with Micromite
Phil Boyce – hands on with the mighty PIC-powered, BASIC microcontroller
Part 24: Counting pulses, rotary encoders and a digital safe
T
his month, we are going to
explore three useful MMBASIC
commands that relate to counting
digital pulses. Using these built-in
commands greatly simplifies tasks such
as measuring the frequency of a signal,
measuring the time period of a pulse
cycle, or simply counting the number of
pulses present on an input pin.
Linked to these topics is something that
follows on nicely from last month, where
we used a rotary potentiometer to generate
a voltage between 0V and 3.3V, which
in turn was used to control the position
of a servo actuator arm. Several readers
contacted us and asked if there was an
alternative to a potentiometer; something
that can instead be continually turned in
either direction (unlike a potentiometer
which is mechanically limited – typically
to around 270°‚ not even a complete
360° revolution). This is where rotaryencoders come into play, and if you have
never used one before, they can be an
extremely useful input device. To make
this a fun, we will show you how to use
a rotary encoder to simulate entering a
digital safe combination number.
What exactly are digital pulses?
Digital pulses comprise transitions
between low and high logic levels on a
signal line. The result is a digital signal.
These can vary considerably, yet are often
simply drawn as the examples shown in
Fig.1. The pulses in a digital signal can be
repetitive and symmetrical; an example
is a square-wave – see Fig.1a. Here they
are shown with a fixed frequency (ie, the
length of a pulse cycle is constant), and
with a duty cycle of 50% (meaning that
for 50% of the pulse cycle, the logic level
Questions? Please email Phil at:
contactus<at>micromite.org
50
is high, and for the remaining
P ulse cycle
time it is at a low logic level).
We have seen, and used,
square-waves earlier in the
1b
series when we used a PWM
signal to drive a piezo sounder
to generate musical notes.
1c
Pulses can also be repetitive
but non-symmetrical ie, where
the frequency is constant, but Fig.1. Examples of various digital signals. 1a represents
the duty cycle is not 50% – a square wave, meaning a duty cycle of 50%. 1b
see Fig.1b. A great example represents a digital signal with the same frequency (ie,
of this is a servomotor signal fixed time-cycle) as 1a, but with a lower duty-cycle. 1c
(ie, PWM signal) where, as is a random signal with a varying frequency (and cycle
we saw last month, the duty time period) and with varying duty-cycles.
cycle controls the position of a
servo motor actuator arm. Digital pulses
that the boundaries of each pulse cycle are
may also be random (ie, non-repetitive
indicated by the dotted lines in Fig.1a and
and non-symmetrical) – see Fig.1c where
Fig.1b. In terms of logic-level transitions,
neither the frequency nor the duty cycle
a pulse cycle in a digital signal is shown
is constant.
in Fig.1 as starting with a low-to-high
Consider each of these digital signals
transition followed by a high-to-low, and
being drawn as a graph where the x-axis
finishes on the next low-to-high transition
represents time, and the y-axis represents
(which is effectively the start of the next
the digital logic level; ie, either a logic
pulse cycle, and so on…). Understanding
high (3.3V) or logic low (0V). The point
this concept of a pulse cycle allows us
here is that at any moment in time, the
to measure two important parameters –
state of the digital signal can be considered
time period and frequency – by simply
as either a low or a high logic state.
detecting logic-level transitions.
If we were to use a Micromite input
pin to read the logic level of a digital
Pulse time-period
signal, then by detecting the transitions
So, having just explained what a pulse
between the low/high states within the
cycle is in terms of logic-level transitions,
signal, we can start to measure certain
it now makes it easy to explain the pulse
parameters about the digital signal. We’ll
time period (sometimes referred to as ‘cycle
discuss the theory first and then look at
time’). The time period is simply the time
the MMBASIC commands that simplify
taken to complete one pulse cycle. In other
the whole process.
words, relating to the square-wave pulse
cycle highlighted in bold in Fig.1, it is the
time taken between two consecutive lowPulse cycle
to-high logic-level transitions. More on
A pulse cycle within a digital signal can
this later when we discuss the MMBASIC
be considered as a ‘complete wave’ that
command to measure this timing.
simply comprises a high-level logic pulse
and also a low-level logic pulse (it doesn’t
matter which comes first). Fig.1a has one
Signal frequency
square-wave pulse cycle highlighted in
Frequency is often regarded as the number
bold to make this a little clearer. Note too
of pulses per second, and it is measured
Practical Electronics | January | 2021
The SETPIN command
As we have seen earlier in this series, the
SETPIN command is used to configure a
Micromite pin to behave in a certain way.
The simplest syntax of this command is:
SETPIN pin-number, configuration,
option where:
pin-number is the value of the physical
pin number on the Micromite chip. It
must be a valid value otherwise an error is
generated (see the Micromite User Manual
for specified values).
configuration is a parameter that
determines the function of the specified
pin. When we first introduced the SETPIN
command early on in the series we used
it to define a pin as a digital input with
SETPIN x,DIN (where x is a valid pin
number) and used SETPIN x,DOUT to
define a digital output. Last month, we
also used SETPIN x,AIN to define an
analogue input pin to which we connected
a potentiometer, which supplied an
analogue voltage between 0V and 3.3V.
Fig.2. This rotary encoder comes with
a built-in RGB LED and a push-button
(activated by pressing on the shaft).
A breakout board is available, making it a
breadboard-friendly device.
in hertz (abbreviated to ‘Hz’); but more
technically correct, it is the number of
complete pulse cycles per second. To
determine the frequency of a digital signal,
we could start a ‘one-second timer’ on
a low-to-high transition, and then count
the number of subsequent low-to-high
transitions while the timer is ‘active’.
When the one-second interval is up,
the count reached would represent the
frequency (in hertz) of the digital signal.
An alternative is to use the wellknown equation: Freq = 1/(time period)
If we measured a time of 0.1 seconds for
a single pulse cycle, then the measured
frequency would be 1/0.1 = 10Hz. Note
that by using the equation method, we
do not have to wait for the ‘one-second’
timer duration.
The theory described above shows
that for MMBASIC to measure a time
period or the frequency of a digital signal,
all it needs to do is detect logic-level
transitions and accurately measure the
time between such transitions.
We could write a BASIC program to
do this, but what if we want to measure
a high frequency signal – there would
come a point where our program code
would simply be too slow to keep
up. To overcome such a limitation,
MMBASIC has three commands built
into the firmware that automatically
detect these logic-level transitions at
an extremely fast rate.
Practical Electronics | January | 2021
option is an optional parameter that
may define further details; for example,
previously we have used PULLUP or
PULLDOWN in conjunction with DIN when
using a push-button as an input. This
avoided having to use a physical resistor
to tie the input signal to a default logic
level (with a push of the button then
setting the opposite logic level).
So, why have we explained all this?
The answer is that the pulse-counting
commands that we are exploring this
month are also implemented with the
SETPIN command, but with different
configuration parameters.
The FIN, PIN, and CIN parameters
The SETPIN command pin-number
parameter must be a valid value, and
referring to the Micromite User Manual,
it explains that four pins (pins 15-18) are
valid for use as ‘COUNTing’ inputs on the
28-pin Micromite. Note that ‘COUNTing’
pins means that FIN, PIN and CIN can be
used on any of these pins (and not just
the counting (CIN) functionality). Now
let’s demonstrate each in turn, starting
with how the MKC can measure the
frequency of a digital signal.
Note that the voltage levels of any
digital signal that we wish to measure
must not exceed 5V, and ideally be at
3.3V for the MKC. If you wish to measure
a digital signal that has a higher voltage,
then simply add a potential divider
between the high-voltage signal and 0V.
For our demonstration purposes, we will
simply use a Micromite output pin as the
source of the digital signal, and so it will
not exceed 3.3V for a high logic level.
Using FIN
To demonstrate how to measure the
frequency of a digital signal, we will use
pin 16 as the input pin. We could also use
pin 15, 17 or 18, but pin 15 may already
be in use if you have a touch-screen
connected and enabled. For a digital test
signal, we will use the PWM command to
output a square wave on pin 4. There
is no diagram for this circuit, since all
we need to do is connect a jumper wire
between pin 4 and pin 16. Once you
have done this, connect your MKC to
your computer, start the Terminal app,
and enter the following:
Freq=2000
SETPIN 16, FIN
PWM 1, Freq, 50
DO
PRINT PIN(16)
LOOP
Before you RUN the code, let’s explain
what we’re doing. The first line sets a
variable named Freq with a value of
2000. This will be the frequency (in hertz)
of the generated square wave from the
PWM pin (ie, the frequency of the digital
test signal).
The second line configures the
appropriate input pin (pin 16) to which
we are connecting the data signal that is
having its frequency measured. The third
line starts to output a square wave on
pin 4 (PWM channel 1A). It is a ‘perfect’
square wave with a 50% duty-cycle; and
the frequency is set to the value stored in
the Freq variable. Next, a DO…LOOP, in
which we continually PRINT the value
of PIN(16) on the terminal screen. Pin
16 is configured with the FIN parameter,
so when you PRINT PIN(16) you don’t
get the logic value (as you would if we
configured pin 16 with DIN), but instead
the firmware measures the frequency
by counting the number of low-to-high
transitions that occur over one second.
RUN the program and you should see is a
stream of ‘0’s (zeros) initially displayed on
the screen, followed possibly by a stream
of values close to 2000, and finally after
one second it should settle on a stream
of 2000. If you do not see this, check
your code matches that shown above,
and also check you have pin 4 and pin
16 connected to each other. Note that
the 2000 shown is a value in hertz; ie
is equal to 2kHz.
Gate time
The reason for the initial zeros (and
potentially a few non-2000 values) is that
there is a one-second period of time during
which the firmware is busy counting the
low-to-high transitions in the background.
This period of ‘counting time’ is referred
to as the ‘gate time’; it must elapse before
51
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
|