This is only a preview of the February 2017 issue of Silicon Chip. You can view 44 of the 104 pages in the full issue, including the advertisments. For full access, purchase the issue for $10.00 or subscribe for access to the latest issues. Articles in this series:
Items relevant to "GPS-synchronised Analog Clock Driver":
Items relevant to "Ultra-low-voltage Versatile LED Flasher":
Items relevant to "El Cheapo Modules from Asia - Part 4":
Items relevant to "High Power DC Motor Speed Control – Part 2":
Items relevant to "New SC200 Audio Amplifier – Part 2":
Purchase a printed copy of this issue for $10.00. |
Getting Started
with the Micromite
Want to learn how to program a microcontroller? There’s no easier way
to start than with this guide to using the Micromite. With this easy-tofollow article, all you need is a Micromite chip and a couple of hours
and you can become an embedded programmer. Part 1 – by Geoff Graham
T
he Micromite, in its various
configurations, has become a
big hit with thousands built. Readers have used it for jobs ranging from
controlling a heating element through
to the brains behind an intelligent
amplifier/tuner.
But there are still many people who
would love to “get into it” but don’t
know how to program in BASIC (or any
other computer language). Is this you?
This tutorial will guide you through
the basics of using the Micromite,
programming in the BASIC language
and show you how to get the Micromite doing something useful almost
straight away.
We’ll start with some small, easy
programs and progress to learning a
few of the more advanced features
which make the Micromite so versatile.
Silicon Chip readers should be familiar with the Micromite by now.
Essentially, it is a super-fast 32-bit
microcontroller programmed with an
advanced BASIC interpreter called
MMBasic.
You use MMBasic to write your programs and because it is designed to be
easy to use, you can get your project
running in far less time than if you
were writing in a complex language
like C or assembly.
To run the examples below, you can
use a bare Micromite chip with just
one capacitor, one resistor and a 3.3V
power supply, as shown in Fig.1.
However, we strongly suggest that
you put together the Micromite LCD
BackPack, as described in the February
20 Silicon Chip
2016 issue as this will be required for
some of the examples in subsequent
articles in this series.
The BackPack can do much more
than a bare Micromite, thanks to its
2.8-inch LCD touchscreen and it has
been extremely popular, with around
1000 built! So if you don’t already have
an LCD BackPack, we suggest you put
one together.
Regardless, once you have your
Micromite up and running, you will
need to connect it to your computer using a USB/serial adaptor and
terminal emulator, as described in
the February 2016 construction article and also in the side-panel later
in this article.
Once you’ve done that, you can
try out all the example code in this
article.
When you have it set up and working, wire up a LED to the BackPack’s
pin 14 (as shown in Fig.2) and load
2 x AA
OR
3.3V DC
SUPPLY
+2.3V to +3.6V <at> 26mA
1
28
27
8
28-PIN
MICROMITE
the following program using MMEdit:
SETPIN 14, DOUT
DO
PIN(14) = 1
PAUSE 200
PIN(14) = 0
PAUSE 300
LOOP
Run it (by clicking the icon of the
running man in the toolbar) and you
should see the LED flashing twice per
second (ie, 2Hz). In microcontroller
circles, flashing a LED is pretty much
the most basic test program you can
write, a sort of “hello world” program. It demonstrates that your chip
is running correctly and you are able
to program it and control its I/O pins
properly.
This is the hardest part; from now on
you can simply build a program pieceby-piece on this foundation, until you
have it doing what you want.
Fig.1: the best option for
experimenting with the examples
in this tutorial is the Micromite
LCD BackPack but if you wish to
just use the 28-pin Micromite on a
breadboard, this is the basic circuit
necessary to get it going. Note that
the capacitor must be tantalum or
ceramic type.
20
10µF 6V
Console TX
Console RX
CERAMIC
OR
11
12
13
47µF 6V
19
TANTALUM
siliconchip.com.au
This short program works by first
configuring the pin connected to the
LED as a digital output (“DOUT”). It
then enters an endless loop (DO …
LOOP) where it turns the LED on and
off with pauses in between.
The full syntax of the initial SETPIN command is:
SETPIN nn, mode
Where “nn” is the pin number on the
Micromite to configure and “mode” is
how you would like the pin to be configured. The mode can be:
AIN – analog input (ie, measure a
voltage between 0V and 3.3V)
DIN – Digital input (ie, sense low
[~0V] or high [~3.3V])
FIN – Measure the frequency of the
signal on pin
PIN – Measure the period (ie, the
time between positive going edges) of the signal on the pin
CIN – Count the number of pulses
on the pin
DOUT – Digital output (either held
low [~0V] or high [~3.3V])
Note that the pin number “nn” refers to the physical pin number of the
chip as shown in the data sheet. This
makes it easy for you to cross-reference
a component connected to the chip
with the programming commands that
will manipulate it.
We will go through the other modes
later but all you need to know for now
is that the first line of the program sets
pin 14 to be a digital output. To make
that pin go high, you assign a non-zero
number to it, as in “PIN(14) = 1”. To
make it go low, you assign the value of
zero to it, as in “PIN(14) = 0”.
The I/O pins on the Micromite
can supply a reasonable amount of
current for driving external components (about 10mA each) and as the
LED will only draw about 4mA, due to
its series current-limiting resistor, that
Fig.2: if you are using
the Micromite LCD
BackPack, this is how
you should connect the
LED to try out some of
the examples. You can
plug the BackPack into a
solderless breadboard or
you can directly connect
to the BackPack I/O pins
as shown here.
Note
CTRL-C can get you out of all
sorts of difficult situations so
remember it because you will find
useful at some time in the future.
is well within the chip’s capability.
PAUSE command
The PAUSE command in our example program does exactly what its
name suggests, ie, causes the program
to pause or wait for a certain amount
of time. This time is expressed in milliseconds, so PAUSE 200 will suspend
the running of the program for 200ms
or one fifth of a second.
You need this delay because the
BASIC program runs quite fast and
without the PAUSE commands, the
LED would flash at such a rate that
you would only see a dim light. You
can verify this by entering the program
without the PAUSE commands:
SETPIN 14, DOUT
DO
PIN(14) = 1
PIN(14) = 0
LOOP
If you attach an oscilloscope to pin
14, you will see that your BASIC program is toggling the output at about
9kHz. There are four commands being
executed in this loop, suggesting that
each command requires an average of
28µs to execute.
Note though that if you run this same
program on the Micromite Plus (eg,
the Explore 64, Explore 100 or Micromite Plus LCD BackPack), it will run
faster, which is a good demonstration
of why it’s a bad idea to rely on execution speed for program timing.
Another part of this program that
needs explanation is the DO … LOOP
construct. This forms an “endless loop”
which causes the contained commands
to be repeated over and over forever!
When MMBasic reaches a LOOP command, it searches backwards for a
matching DO command and then jumps
back to there and executes the following
commands again.
Fig.3: pin connections for the microUSB-to-serial converter. Note that the RX pin
from the converter goes to the TX pin on the board, and vice-versa.
siliconchip.com.au
February 2017 21
Setting up the Micromite
As mentioned at the start of the article, the best set-up to play with the
examples in this series of articles is
the Micromite LCD BackPack, which
was featured in the February 2016 issue of Silicon Chip. This simple project uses fewer than ten components
and can be built in half an hour. It
includes a 3.3V power supply, 28pin Micromite and LCD touchscreen.
In future tutorials, we will cover
drawing graphics on the display and
using the touch interface, so the Micromite LCD BackPack will enable
you to follow the examples and experiment for yourself.
A complete kit is available from
the Silicon Chip Online Shop, which
includes all the parts you need to
build the BackPack, here: www.
siliconchip.com.au/Shop/20/3321
The February 2016 issue which describes the Micromite LCD BackPack
can also be purchased from:
• w w w. s i l i c o n c h i p . c o m . a u /
Shop/2/3317 (printed copy)
• w w w. s i l i c o n c h i p . c o m . a u /
Shop/12/3330 (online version)
• We can also supply a USB/serial
interface module to connect it to
your computer at the same time:
• w w w. s i l i c o n c h i p . c o m . a u /
Shop/7/3437 (with USB TypeA plug, no cable required)
• w w w. s i l i c o n c h i p . c o m . a u /
Shop/7/3543 (with microUSB
Type-B socket, cable required)
However, you do have the option
of simply plugging a 28-pin Micromite into a solderless breadboard
and use jumper leads to connect
up the LCD display whenever you
needed to. Either choice is viable so
it is up to you. If you would like to
follow this route, you can purchase
just the 28-pin Micromite from the
Silicon Chip Online Shop at: www.
siliconchip.com.au/Shop/9/2908
Connecting to a computer
To program the Micromite using
MMBasic, you can enter commands
and programs via the console. The
console is a serial interface over which
you can issue commands to configure
the chip and edit/run programs.
MMBasic also uses the console to
display error messages; your own
programs can also display messages on the console, and receive user
input from it.
A serial interface consists of two
signals. One, referred to as TX or
TXD (for transmit [data]) carries coded signal data from the device while
the other, called RX or RXD, receives
similarly coded signals. ASCII encoding is used for each character
sent or received.
The speed of transmission is referred to as a baud rate which is
another way of saying bits per second. The Micromite starts up with
its console serial port set to a baud
rate of 38400.
The serial port uses TTL signalling
which means that the signal swings
between zero and 3.3 volts.
To use the serial console, you need
a USB-to-serial converter which
plugs into a USB port on your PC
and on the other end, connects to the
Micromite’s serial console. This provides a virtual COM port on which
your PC can send and receive data
from the Micromite.
Two suitable devices, both using
the CP2102 chip and available from
the Silicon Chip Online Shop, are
mentioned above. The CP2102 and
how it works is described in greater detail in the January 2017 issue.
The picture opposite shows how
such a converter is connected to the
28-pin Micromite on a solderless
breadboard. Note that this photo
shows the Micromite with an independent 3.3V power supply but the
3.3V output on the converter can be
used to power the Micromite.
When the converter is plugged into
your computer and the correct driver
is installed, it will appear as a serial
port (eg, COM29 in Windows). You
then need to start a terminal emulator
on your computer to open the port.
For Windows, we recommend
Tera Term version 4.88 which is a
free download from http://tera-term.
en.lo4d.com Set the interface speed
to 38400 baud as shown in Fig.4 and
connect to the serial port created by
the USB to serial converter.
With this done, apply power to
the Micromite and in the terminal
emulator’s window, you should see
the Micromite’s startup banner as
shown in Fig.5. At this point, you
can enter, edit and run programs
from the command prompt using
nothing more than the terminal emulator and a USB cable.
When your program is running
successfully on the Micromite, you
do not necessarily need the console,
so you can set the Micromite to automatically run its program on startup
(OPTION AUTORUN ON).
However, unless you managed to
get the program perfectly correct the
first time (unlikely), you will find
yourself repeatedly reconnecting to
make one tweak or another, so many
people leave the USB-to-serial converter permanently connected (they
do not cost much).
Troubleshooting
What if it does not work the first
time?
Fig.4 (left): startup
screen for Tera Term,
where the baud rate and
other values can be set
on launch.
Fig.5 (right): startup
banner for the Micromite
running in the Tera Term
console.
22 Silicon Chip
siliconchip.com.au
1) Check your power supply. Is it
3.3V and is it stable and free from
electrical noise? If you have doubts,
you can use two fresh AA batteries in
series as a power source for testing.
Then check that 3.3V is on each pin
shown in Fig.1 and that each ground
pin is correctly connected to 0V.
2) Check the 10µF or 47µF
capacitor connected to pin 20 on
the 28-pin chip or pin 7 on the 44pin chip. As mentioned earlier, this
capacitor must be a ceramic or
tantalum type; an electrolytic
capacitor will not work.
3) Has the chip been properly
programmed? If you programmed
it yourself, check that the programmer did report that the programming
operation was successful. A current
draw of about 26mA means that the
chip is working correctly and running the BASIC interpreter. Less
than 10mA indicates that MMBasic
is not running and:
• a power or ground connection is
faulty;
• the 10/47µF capacitor is faulty or
not connected or;
• the chip was not programmed
correctly.
If you have a current draw of about
26mA, the fault is most likely with
the USB-to-serial converter or your
terminal emulator.
To check these two elements, disconnect the serial connections from
the Micromite and short the TX and
RX pins of the converter together.
When you type something on the
keyboard into the terminal emulator,
you should see the same characters
echoed on the screen.
If not, diagnose and correct the
error in your USB-to-serial converter and terminal emulator before
proceeding.
If the above test is OK (ie, keystrokes echo on the screen), the only
possible remaining fault is in your
connection of the USB-to-serial converter to the Micromite. Check that
the TX pin on the converter goes to
the Micromite’s RX pin and that RX
on the converter goes to the Micromite’s TX pin, as illustrated in Fig.3.
Loading your program
If you prepare your program on
a desktop (or laptop) computer,
you can transfer it to the Micromite
siliconchip.com.au
The Micromite works well with a simple solderless breadboard. In this photo
it is running the flashing LED example (with the LED connected to pin 15).
using either the AUTOSAVE or XMODEM commands.
The AUTOSAVE command puts
the Micromite into a mode where
anything received on the console
will be saved to the program memory. This means that you can simply
copy the text and paste it into the
terminal emulator (eg, Tera Term)
which will send it to the Micromite.
From the Micromite’s perspective,
pasting text into the terminal emulator is the same as if a high speed
typist was typing in the program.
To terminate the AUTOSAVE
command, press CTRL-Z in the terminal emulator (ie, hold CTRL and
then press Z) and the Micromite will
save the program to flash memory
and return to the command prompt.
The XMODEM command is a little
more complex. It uses the XModem
protocol to transfer the data which
includes an integrity check.
The full command is XMODEM
RECEIVE, which instructs the Micromite to look for an XModem connection on the console. After running
this command, you then instruct your
terminal emulator to send the file using the XModem protocol.
When the file has been sent, the
Micromite will save it in program
memory and return to the command
prompt.
One of the most convenient methods of creating programs and sending them to the Micromite is to use
the MMEDIT software. This program
was written by Silicon Chip reader
Jim Hiley in Tasmania. It can be installed on Windows or Linux and it
allows you to edit your program on
your PC and transfer it to the Micromite for testing with a single click.
MMEDIT is easy to use with colour-coded text, mouse-based cut and
paste and many more features such
as bookmarks and automatic indenting. Because the program runs on
your PC, you can save and load your
programs to and from the computer’s
hard disk.
It can be downloaded from Jim’s
website at: www.c-com.com.au/
MMedit.htm It is free, although he
would appreciate a small donation.
The Micromite also has its own
built-in editor. This relies on you
using a terminal emulator that is
VT100 compatible (eg, Tera Term)
on your desktop computer and to invoke it you use the EDIT command.
If you are used to an editor like
Notepad in Windows, you will find
that the operation of this editor is
familiar. The arrow keys will move
your cursor around in the text and
the other keys on your keyboard will
do what their titles suggest.
The editor is a very easy method
of developing a program. With it,
you can write your program on the
Micromite then save and run it from
within the editor. If your program
should stop with an error, you can
jump back into the editor again with
the cursor positioned at the line that
caused the error. As a result the edit/
run/edit cycle is very fast.
February 2017 23
Normally, either the DO portion or
the LOOP portion will have a condition attached that will tell MMBasic
when to terminate the loop but in this
case, there is no terminating condition, so the program will loop forever.
This introduces another subject –
how do you stop something like this
when it is running? The answer is
that you use the CTRL-C sequence on
the console, which is done by holding down the CTRL key when pressing the C key.
This is called the break key or character. When you type this on the console’s input, it will interrupt whatever program is running and immediately return control to the command
prompt.
The PRINT command
One of the most frequently used
commands in the BASIC language
is the PRINT command. Its job is
simply to display something on the
console. This is commonly used to
tell you how your program is running (and can help to find bugs) and
the displayed message can be something simple, like “Pump running” or
“Total Flow: 23 litres”.
In its simplest form, the PRINT command will just print whatever follows
it. So, for example:
PRINT 54
Will display the number 54 on the
console, followed by a new line (ie, so
that the next print command will display its output below). The data to be
printed can consist of “expressions”,
which refers to something that needs
to be calculated. We will cover expressions in more detail later but as an example, consider the following:
PRINT 5*(9+2)
This will print the number 55 (“*”
means multiply; “+” obviously means
addition).
The following program illustrates
the use of the PRINT command. It
will measure the voltage on pin 4 of
the Micromite and display the reading on the console repeatedly, once
per second:
SETPIN 4, AIN
DO
PRINT PIN(4)
PAUSE 1000
LOOP
This program is similar to our LED
24 Silicon Chip
flasher but in this case, we have configured pin 4 to be an analog input
with the “SETPIN 4, AIN” command.
To read the voltage on the configured pin you just use the “PIN(4)”
function to get the voltage, which the
“PRINT” command will then display
on the console. You can test this program by connecting various 1.5V cells
between pin 4 and GND (positive end
to pin 4) and noting how the reading
will change. Congratulations, you have
built a digital voltmeter with five lines
of BASIC code!
You can also use the PIN() function
to read the state of a digital, frequency,
period or counter input.
Note that for a pin configured as
an analog input, MMBasic returns
the value in volts but it assumes the
power supply rail is exactly 3.3V, as
this is used for the reference input to
the analog-to-digital converter. If your
power supply is not exactly 3.3V, the
returned value will have to be adjusted
as shown later in this tutorial.
Variables
Before we go much further, we need
to define what a “variable” is as they are
fundamental to the operation of most
computer languages, including BASIC.
A variable is simply a place to store an
item of data (ie, its value) for later use.
Variables can be any one of three
types. The most common is a floating
point (decimal) number and this is
the default if the variable type is not
specified. The other two types are integer (ie, whole number) and string (ie,
text) and we will explain them later.
7, 3.45, -99.0, .012 and 120.09 are all
valid floating point numbers. “Floating” refers to the fact that the decimal
point does not have a fixed number of
digits either before or after it.
When a number is stored in a variable, the variable can then be used in
place of the number itself. It simply
represents the last value assigned to
it. As a simple example:
A=3
B=4
PRINT A + B
This will display the number 7. In
this case, “A” and “B” are variables
and MMBasic used their current values in evaluating the expression after
the PRINT statement.
BASIC will automatically create a
variable when it first encounters it,
so the statement “A = 3” both creates
a floating point variable (the default
type) with the name “A” and then it
assigns it the value 3.
The name of a variable must start
with a letter, while the remainder of
the name can use letters, numbers, underscores or full stops. The name can
be up to 32 characters long and the
case of the letters used (ie, lower case
or upper case [capitals]) is not important. Here are some examples of valid
variable names:
Total_Count
ForeColour
temp3
count
The IF statement
Making decisions is at the core of
most computer programs and in the
BASIC language, that is usually done
with the “IF” statement. This is written almost like an English sentence:
IF condition THEN action
The condition is usually a comparison such as testing for equality, less
than, greater than, etc. For example:
IF Temp < 20 THEN HeaterOn
“Temp” would be a variable holding
the current temperature and HeaterOn
refers to a section of the program containing commands which perform the
action(s) necessary to turn the heater
on (this is called a subroutine and will
be explained later). There is a wide
range of comparisons that you can use:
= equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
<> not equal to
These can be combined using
“AND” and “OR”, for example:
IF Temp > 20 AND Temp < 30 THEN
Temp_OK = 1
You can also add an “ELSE” clause
which will be executed if the condition
tested false. For example, this program
will turn on a LED connected to pin
14 if the voltage on pin 4 is more than
2V and turn it off if it is less:
SETPIN 4, AIN
SETPIN 14, DOUT
DO
IF PIN(4) > 2.0 THEN PIN(14) = 1
ELSE PIN(14) = 0
LOOP
This program will spin at high
siliconchip.com.au
speed, constantly setting the output
high or low but that does not matter because the program has nothing else to
do and it means that the LED will react
instantly to any change to the voltage
on pin 4. Note that in an IF statement
like this with an ELSE clause, one of
the two commands is always executed
but never both.
The previous examples use singleline IF statements but you can also
use multi-line IF statements for cases
where multiple commands need to be
executed. They look like this:
IF condition THEN
TrueAction1
TrueAction2
...
ELSE
FalseAction1
FalseAction2
...
ENDIF
Generally, the single-line IF statement is used for simple situations
while the multi-line version is much
easier to understand if the commands
required are numerous and/or long.
Note that the multi-line version
must be terminated with the ENDIF
command; this tells MMBasic where
the commands associated with the
ELSE leg have terminated.
You can also have the multi-line IF
statement without an ELSE section.
For example:
IF condition THEN
TrueAction1
TrueAction2
...
ENDIF
An example of a multi-line IF
statement with more than one action is:
SETPIN 4, AIN
SETPIN 14, DOUT
DO
IF PIN(4) > 2.0 THEN
PIN(14) = 1
PRINT “Voltage high”
ELSE
PIN(14) = 0
PRINT “Voltage low”
ENDIF
LOOP
Note that in the above example,
we indented (added spaces before)
each action to make it clearer which
part of the IF structure it belonged
to. While this is not mandatory it
siliconchip.com.au
does make a program much easier
to understand and is highly recommended. Hence, all our examples have
been indented.
Remember that after only a few
months, a program that you have written will have faded from your mind
and will look strange when you pick
it up again. Accordingly, you will end
up thanking yourself if you indent
consistently.
Measuring voltages
We mentioned measuring voltages
previously but there are some details
that you need to know before you can
properly use this feature.
The 28-pin Micromite (as used in
the LCD BackPack) has 10 I/O pins
that are capable of voltage measurement and the 44-pin Micromite has 13.
Naturally, the 64-pin and 100-pin
Micromite Plus chips have even more.
They are marked as ANALOG on the
pin diagrams. Remember that you
need to use a command like this to
set an I/O pin (number “nn”) to be an
analog input:
SETPIN nn, AIN
The input voltage range is from
zero to whatever the supply voltage
is (normally 3.3V). Assuming your
supply is stable but not exactly 3.3V,
you can measure its actual voltage and
compensate to give accurate measurements as follows. In this example, let’s
say you measure it as exactly 3.17V:
PRINT PIN(4) / 3.3 * 3.17
To avoid having to put the supply
voltage all over the program, you can
set it as a constant variable at the top
of your program and then just refer to
the constant, like this:
CONST SUPPLY_VOLTAGE = 3.17
…
PRINT PIN(4) / 3.3 * SUPPLY_
VOLTAGE
Taking this concept a step further,
if you’re doing a lot of analog measurements, the following will make the
code a little simpler and also faster:
CONST SVFACT = 3.17 / 3.3
…
PRINT PIN(4) * SVFACT
To measure voltages greater than
the supply voltage, you will need to
connect a voltage divider between
the voltage to measure, the analog
pin and ground. Rather than use
precision resistors for this, you can
simply apply a known voltage to
the divider and get the Micromite to
display what it measured on the
input (ie, PRINT PIN(4)).
Then, if you use a digital voltmeter
to measure the actual voltage at the
input of the voltage divider, you can
scale future readings from that pin to
give the correct value by using the following expression:
PRINT PIN(nn) * (Vmes / Vmm)
Where “Vmes” is the measured input voltage and “Vmm” is the reading
returned by the MMBasic PIN() function. This approach will also automatically correct for a supply voltage that
is not exactly 3.3V, so you don’t need
to do that separately (and yes, you can
use a constant variable to simplify this
command, as demonstrated above).
Note that to retain the accuracy
of the reading, the source resistance
for an analog input pin needs to be
10kW or less. This means that in most
circuits, the bottom resistor in the
voltage divider should be no more
than 10kW.
To measure very small voltages accurately (well under 1V), you may
need an amplifier to bring the input
voltage into a reasonable range for
measurement.
Fig.6 shows a typical arrangement
using the popular and inexpensive
LM324 quad operational amplifier.
The LM324 can operate from a single 5V supply (as provided by the
Micromite LCD BackPack on CON2)
and contains four identical amplifiers
in the one low-cost 14-pin package.
The gain of this amplifier is determined by the ratio of R2 to R1 plus 1
(ie, R2 ÷ R1 + 1) and using the components in Fig.6, the gain is 101. This
number can be used in the BASIC program so that the readings are scaled
to represent the input voltage. For
example:
PRINT PIN(4) / 101
Alternatively, as with the voltage
divider, you could just measure the
input voltage and pin reading simultaneously and use the ratio to scale
future readings. This would also compensate for resistor value and supply
voltage tolerances.
February 2017 25
Amplifier Gain = 1 + R2
R1
LM324
A OUTPUT
1
A -INPUT
2
A +INPUT
3
1
4
+
+
14
D OUTPUT
13
D -INPUT
12
D +INPUT
11
GND
10
C +INPUT
V+
4
B +INPUT
5
B -INPUT
6
9
C -INPUT
B OUTPUT
7
8
C OUTPUT
+
2
3
+
(Top View)
DO loops
Returning to our example program
earlier, it used a “DO LOOP” to repeatedly step through a set of commands
which is a common requirement in
computer programs.
In the example program, the DO
LOOP never stopped running (until
CTRL-C is pressed). However, it is
more common to provide a test which
will terminate the loop at some point.
For example:
count = 0
DO WHILE count < 10
count = count + 1
PRINT count
LOOP
This program will simply print
the numbers from one to ten. The
key aspect is the WHILE test which
ensures that the program will only
keep looping while the value of
“count” is less than 10. When the
value of count equals or exceeds 10,
MMBasic will terminate the loop and
continue on with the code after the
LOOP command.
The conditional test is the same as
for the IF command so you can test
for equality, less than, greater than
and so on. As another example, you
might need to delay the start of a program for two seconds to allow external
circuitry to settle. This could be done
with this loop:
DO WHILE TIMER < 2000
LOOP
“TIMER” is a built-in MMBasic
function which returns the number
of milliseconds since the Micromite
was powered up. This empty loop
will simply “sit there and spin”
26 Silicon Chip
With the values shown the
gain will be 101 and therefore
a 32mV input will result in a full
scale reading.
5V POWER
1
+
2
CON2
Input
(0-32mV)
Fig.6: to measure small voltages
you need an amplifier and this
shows how to use the LM324 quad
op amp. It can operate from a
single 5V supply (as provided by
the Micromite LCD BackPack on
CON2) and contains four identical
amplifiers in the one 14-pin package.
until the value of TIMER reaches 2000ms, thereby providing the
required delay.
Note that a similar effect could be
achieved with the PAUSE command,
however, consider that if you had other commands to run before the loop,
the time taken to execute them would
be taken into account by this method.
Thus this method which would give
a faster start-up while still providing
the required settling time.
An important feature of the above
loops is that the test is made before
the loop is executed and that in turn
means that if the test is initially false,
the contents of the loop will not be executed at all, not even once.
However, if you do want the loop’s
contents to be executed at least once,
you can position the test at the end of
the loop instead, as follows:
DO
statement
statement
LOOP UNTIL condition
Micromite
4
3
LM324
2
1
10kΩ
Input Pin
11
R2 10kΩ
R1
100Ω
In this case, the statements within
the loop are executed at least once and
only then is the condition is tested.
Also note that because the keyword
“UNTIL” is used, the test is reversed;
if it is true the loop will be terminated, otherwise it will be repeatedly
executed until the condition does becomes true.
This is our previous example rewritten to place the test at the end of
the loop:
count = 0
DO
count = count + 1
PRINT count
LOOP UNTIL count = 10
Both forms of the “DO LOOP” do
the same thing, so you can use whatever structure fits with the logic that
you want to implement and is the most
clear to write and interpret.
Next month we will continue the
tutorial with drawing graphics on an
LCD display panel, FOR loops, expressions and much more.
SC
Getting more information on the Micromite
The Micromite is a fully functional computer with a multitude of facilities
and the Micromite User Manual which describes it adds up to almost 100
pages. This manual is the ultimate reference for the Micromite and covers everything from the I/O pins through to functions that you might only
need in specialised circumstances. It is in PDF format and available for
free download from the Silicon Chip website (at www.siliconchip.com.au/
Shop/6/2907) and the author’s website (http://geoffg.net/micromite.html).
This tutorial (including the parts to come in future months) will go through
many aspects of the BASIC language but it cannot cover everything. For
example, many commands have additional features that are only used in
special circumstances. So it would be worthwhile downloading the manual and having it handy as you read through the tutorial. That way you can
explore the full detail of a command that might interest you.
siliconchip.com.au
|