This is only a preview of the March 2017 issue of Silicon Chip. You can view 48 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. Items relevant to "All-new Swimming Pool Lap Counter":
Items relevant to "The Stationmaster: walk-around PWM train control":
Articles in this series:
Items relevant to "New SC200 Audio Amplifier - Part 3":
Items relevant to "El Cheapo Modules, Part 5: LCD module with I²C":
Purchase a printed copy of this issue for $10.00. |
Part 2 –
Getting Started
with the Micromite
Last month we introduced the input/output system, making
decisions (IF...THEN...ELSE...) and looping (DO...LOOP). One of the
outstanding features of the Micromite is its ability to drive a variety
of LCD panels, so this month we concentrate on graphics as well as
introducing expressions and FOR/NEXT loops.
by Geoff Graham
T
he standard 28-pin and 44-pin
Micromites can drive 2.2, 2.4
or 2.8-inch LCD panels. These are
manufactured in enormous quantities for common consumer devices
such as air conditioners and coffee
makers and as a result they are very
cheap. The more powerful version of
the Micromite (the Micromite Plus)
can drive an even wider range of
displays from 1.44 inches to 8 inches
(diagonal).
All these displays use TFT (Thin
Film Transistor) technology which
means that every pixel has an associated switching transistor integrated
into the LCD panel. This provides a
bright and colourful display which
the Micromite can use to show text,
lines, circles etc in thousands of different colours. Most of these displays
also provide a touchscreen function
to make user input simple.
Using these features, even the simplest of projects can sport a colourful
display for a wide range of information such as temperatures, voltages
and levels.
64 Silicon Chip
The best way to experiment with
LCDs and the Micromite is to build
the Micromite LCD BackPack as mentioned in last month’s tutorial and described in the February 2016 issue of
Silicon Chip.
This simple project uses less than
ten components and can be built in
half an hour. It includes the 3.3V
power supply, a 28-pin Micromite
and a touch sensitive LCD panel. A
kit of these parts is available from the
Silicon Chip Online Shop.
The remainder of this tutorial assumes that you have a running Micromite with a suitable display attached. If
you are having trouble getting this setup working, please refer to last month’s
article or the February 2016 issue.
The PIXEL command
The 2.2-inch, 2.4-inch and 2.8-inch
LCD panels supported by the Micromite have 320 columns and 240 rows
of pixels (320 x 240, a total of 76,800
pixels), with each pixel capable of displaying one of 65,536 (216) different
colours. You can control any of these
pixels using the PIXEL command. The
syntax of this command is:
PIXEL x, y, colour
The first two parameters are the coordinates of the pixel that you wish to
change and the third is the colour that
you want for the pixel.
The coordinates are expressed in
pixels with x being the horizontal
axis and y the vertical. The top left
of the screen has the coordinate
x = 0 and y = 0.
Both the x and y coordinates
increase as you move to the right and
down the screen and accordingly
x = 319 and y = 239 are the coordinates
of the bottom-right corner of the screen
and the bottom-left is x = 0 and y = 239.
As an example, to make the pixel at
the centre of the screen turn yellow,
try entering this:
PIXEL 160, 120, 16776960
Don’t worry if you cannot see it;
each pixel is quite small – so you may
need a magnifier!
Now you might be wondering how
siliconchip.com.au
the number 16776960 equates to yellow. MMBasic uses a 24-bit number to
define a colour (the same as a desktop
PC). The top eight bits set the intensity
of the red colour, the middle eight bits
the green colour and the bottom eight
bits the blue colour.
Each 8-bit number can range from
zero to 255 (decimal). Zero means
that colour sub-pixel is off while 255
means it is fully lit and the other values relate to intensities between these
two extremes.
Yellow is produced when the red
and green colours are at high intensity and blue is off. Note that colours
produced using additive light work
differently from paint and ink, which
use a subtractive process. For example, with an additive process such as
used in an LCD, red and blue combine
to make mauve, whereas with red and
blue paint or ink mixed together you
get brown.
Anyway, if you calculate the 24-bit
value with red = 255 and green = 255
using binary arithmetic you will get
the number 16776960.
Obviously this is rather clumsy so
MMBasic makes it easy for you with
the RGB() function. This has the form
RGB(red, green, blue) where red is a
number between zero and 255 and similar for green and blue. So you could
rewrite the command to turn on the
pixel with the yellow colour like thus:
Saving Programs
When you save a program to the Micromite (using MMEDIT, XMODEM
or whatever) you might wonder where your program has actually been
saved to. The answer is that it was automatically programmed into the
flash memory of the PIC32 chip.
Yes, the PIC32 includes its own built-in flash programmer! In fact, if
you save a very large program, you might see a delay of a second or two
which is the time needed by MMBasic to program that large amount of
data into the flash memory.
Flash memory is non-volatile which means that it will retain its
contents when power is removed. This might not be important for
a program that does something simple like the examples in this
tutorial but if you have programmed the Micromite to control your garden
watering system you will not want it to lose the program during a blackout. The MEMORY command reports on how much memory has been
used by the program. With a small program of 20 lines it will display
something like this:
Flash:
1K ( 1%) Program (20 lines)
59K (99%) Free
RAM:
1K ( 1%) 4 Variables
0K ( 0%) General
49K (99%) Free
As you can see, the program used little memory. This is another advantage of the Micromite; the relatively huge memory space means that you
can create large and complex programs and still run them on this small and
inexpensive chip. If you do manage to exhaust the Micromite’s program
space or RAM (as we have on occasion), it’s time to move to a Micromite Plus
which also has the benefit of 2.5 times the execution speed of the regular
Micromite. See the Micromite Plus articles in the August-November
2016 issues for more details.
PIXEL 160, 120, RGB(255, 255, 0)
We will cover the details of functions and expressions soon so please
bear with us for a short time.
To make it even more convenient
for you to specify a colour, the RGB()
function allows you to directly name
the colour, so you could also turn the
pixel yellow using this:
PIXEL 160, 120, RGB(yellow)
The colours that you can specify this
way are red, green, blue, yellow, cyan,
purple, white and black (yes, black is
considered a colour!)
The 24-bit value used to specify a
colour has over 16 million variations
but the LCD panel we use can only
show 65,536 (16-bit) colours. This
need not concern you as MMBasic
will automatically choose the closest colour when converting the 24-bit
colour for the LCD.
Some of the displays compatible
with the Micromite Plus are natively
24-bit so you will get the full range of
siliconchip.com.au
colours and the driver will automatically re-arrange the RGB value if it
differs in format from what the LCD
driver IC expects.
Expressions
We have used the term “expression”
before in this tutorial and above we referred to the RGB() function, which is
part of an expression.
In programming languages, “expression” has a specific meaning. An expression is similar to a mathematical
formula and it can be resolved by the
BASIC interpreter to a single number,
text string or value. MMBasic evaluates expressions using the same rules
that we all learnt at school. For example, multiplication and division are
performed first, followed by addition
and subtraction.
This means that 2 + 3 * 6 will evaluate to 20, as will 5 * 4 and 10 + 4 * 3
- 2. If you want to force the interpreter to evaluate parts of the expression
first, you can surround that part of the
expression with parentheses (round
brackets), just as in a mathematical
formula.
For example, (10 + 4) * (3 – 2) will
evaluate to 14 and not 20, as would
have been the case if the brackets were
omitted. Using brackets does not appreciably slow down the program so
you should use them liberally if there
is a chance that MMBasic will misinterpret your expression.
As you would expect, you can use
variables in an expression in exactly the same way as for straight numbers. You can also use functions in
expressions. There are special builtin functions provided by MMBasic,
for example, to calculate trigonometric values.
As an example, the following will
print the length of the hypotenuse of
a right-angled triangle, with variables
“a” and “b” holding the lengths of the
other two sides. The SQR() function
March 2017 65
You can nest FOR loops, one inside
the other. For example, the following
will fill the LCD with the colour red:
FOR y = 0 to 239
FOR x = 0 to 319
PIXEL x, y, RGB(red)
NEXT x
NEXT y
Photo 1: the result of running a single BOX command. The thickness was set to
three pixels, border colour to red and blue colour fill.
returns the square root of a number:
PRINT SQR(a * a + b * b)
The RGB() function introduced
above is another example of a builtin function. MMBasic includes many
functions and a lot of them are mathematically orientated. For example:
SIN(r) – the sine of r (in radians)
COS(r) – the cosine of r (in radians)
TAN(r) – the tangent of r (in radians)
ATAN(r) – the arctangent of r (in
radians)
There are many more functions
available to you and they are all listed
in the User Manual.
Note that in the above functions, the
value passed to them (r) is the angle in
radians. In MMBasic you can use the
function RAD(d) to convert an angle
from degrees to radians (where d is the
angle in degrees).
This leads to another feature of BASIC which is that you can nest function
calls within each other. For example,
given the angle in degrees (ie, d), the
sine of that angle can be found with
this expression:
SIN(RAD(d))
In this case, MMBasic will first take
the value of d and convert it to radians
using the RAD() function. The output
of this function then becomes the input to the SIN() function. This is similar to how a mathematical formula
works, for example, you may have seen
the mathematical expression “f(g(x))”,
where f(x) and g(x) are any two other
66 Silicon Chip
functions. This is known in mathematics as “function composition”.
FOR...NEXT loops
While we are describing the PIXEL
command, it is also a good time to
cover FOR…NEXT loops. These are
similar to the DO…LOOP construction that we described in the tutorial
last month. The difference is that the
FOR…NEXT loop will automatically
increment a variable through each iteration of the loop and will terminate
the loop when that variable exceeds
a set value.
This is a surprisingly common requirement in programming. For example, if you want to draw a horizontal
line across the top of an LCD you can
use the following:
FOR x = 0 to 319
PIXEL x, 0, RGB(yellow)
NEXT x
This starts by creating the variable “x” and assigning it the value
of 0. MMBasic will then execute the
statement(s) within the FOR loop in
the usual order (top to bottom) until
it comes to the NEXT statement. This
tells the BASIC interpreter to increase
the value of “x” by one, go back to
the previous FOR statement and execute the statements within the loop
a second time. This will repeat until
the value of “x” exceeds 319 at which
time the program will exit the loop and
continue with the statements following the NEXT line.
It starts by creating the variable “y”
(the y coordinate) and setting it to zero,
then the inner loop will draw a horizontal line. When this horizontal line
has finished, its loop will exit and the
outer loop will increment “y” by one
and repeat the inner loop to draw another horizontal line. This way the entire screen is covered with a series of
horizontal lines.
In the above examples, the variable
is incremented by one by default, but
you can change this by specifying the
step size. The following example uses
this to draw a series of dots instead of
a continuous horizontal line:
FOR x = 0 to 319 STEP 4
PIXEL x, 0, RGB(yellow)
NEXT x
For every iteration of the loop, the
variable “x” is incremented by four,
which results in every fourth pixel
being turned on.
As an aside, sometimes you may
find it necessary to abort a FOR loop
before all of its iterations have completed. The EXIT FOR command can
be used to do this. When this command
is encountered within a FOR loop the
loop will immediately terminate and
the program will continue with the
very next statement after the associated NEXT statement.
Similarly, the command CONTINUE
FOR will cause execution to immediately skip to the associated NEXT statement and the loop will then continue
with its next iteration (or will exit, if
it was already on the last iteration).
By the way, similar commands
CONTINUE DO and EXIT DO
operate on DO loops, which was
covered last month.
More graphics commands
If you try the above program to
fill the LCD screen with a red colour
you will notice that it is very slow.
This is because the PIXEL command
must be called 76,800 times to turn
on all the pixels on the display and
even though the Micromite is quite
fast, it takes some time to execute the
siliconchip.com.au
command is the CIRCLE command
which, as its name suggests, will draw
a circle. This looks like this:
CIRCLE x, y, r, lw, a, c, fill
Photo 2: the result of three CIRCLE commands. The centre circle is perfectly
round and has a red border that is three pixels thick and is filled with yellow.
The other two are ovals with different aspect ratios (0.5 and 1.8) and colours
(blue and green).
command this many times and repeatedly transfer the necessary instructions to the LCD panel.
For this reason, MMBasic includes
the CLS (CLear Screen) command
which will fill the screen with a specified colour at a much higher speed.
For example, the following will do
the same thing as our above program
using PIXEL but do it in the blink of
an eye:
CLS RGB(red)
You can specify any colour that you
want and if you do not specify a colour the command will fill the screen
with the default background colour
(which is normally black) and thereby
clear the screen.
There are other graphic commands
that you can use which are more convenient than drawing pixel by pixel.
For example, to draw a line you can
use the LINE command which has
the form:
LINE x1, y1, x2, y2, lw, c
x1 and y1 are the coordinates of the
start point of the line and x2 and y2
indicate the end point. lw is the width
of the line (in pixels) and c is the colour to use. Using this command you
can more easily draw the horizontal
yellow line that we did previously
like this:
LINE 0,0, 319,0, 1, RGB(yellow)
siliconchip.com.au
One thing to keep in mind is that
the lw parameter only applies to horizontal or vertical lines, diagonal lines
are always drawn with a line width of
one. Another useful command allows
you to draw a box. It looks like this:
BOX x1, y1, w, h, lw, c, fill
x1 and y1 are the coordinates of the
top left corner of the box and w is the
width (in pixels) while h is the height.
Similarly to the LINE command, lw is
the width of the border (in pixels) and
c is the colour to use when drawing the
sides of the box. The parameter fill is
the colour to use if you want the interior of the box to be filled with a colour.
As an example, the following will
draw a box with the boundary drawn
in red, three pixels thick and it will be
filled with blue (see Photo 1):
BOX 20,20, 280,200, 3, RGB(red),
RGB(blue)
A close relative is the RBOX command which will draw a box with
rounded corners. This is particularly
useful for drawing touch sensitive buttons on the screen (see the lead photo
for an example).
Its syntax is identical to the BOX
command except that instead of the
lw (line width) parameter, it accepts
a parameter called r (radius) which
is the radius of the corners and it defaults to 10 pixels.
The final general purpose graphic
x and y are the coordinates of the
centre of the circle and r is its radius. lw is the width of the line to draw
on the circumference circle, a is the
aspect ratio of the circle, c is the
colour of the line used to draw the
circle and fill is the optional colour
used to fill the circle.
The aspect ratio is a decimal
number which can be a fraction; if
it is exactly one, the circle will be
perfectly circular; if it is less or more
than one, the graphic drawn will be
an oval with either the vertical or
horizontal axis longer than the other,
respectively.
Try the following and you will see
how the command works:
CLS
CIRCLE 160,120, 45,3, 1, RGB(red),
RGB(yellow)
CIRCLE 160,120, 100,1, 0.5,
RGB(blue)
CIRCLE 160,120, 50,1, 1.8,
RGB(green)
In this program, the CLS command
first clears the screen then a circle is
drawn in red with a border three pixels thick. The circle will also be filled
with yellow. Next, a blue oval will be
drawn followed by a green oval, each
oval drawn with a different aspect ratio. Photo 2 shows the result.
A random example
The following example will draw
multiple lines on the screen with
random positions and random colours. It is intended to demonstrate
many of the techniques that we have
covered including variables, expressions, generating colours and the LINE
command.
The program uses the built-in RND
function, which generates a fresh pseudo-random number every time it is
used. Pseudo-random means that the
numbers will not come in an obvious
sequence but they are not truly random. The output of RND() is a decimal
from zero to just below one; it never
actually generates the number one but
you might get 0.999999.
Normally, the result from RND() is
manipulated in some way to give a
“random” number in a specific range
of values. For example, if you want to
March 2017 67
it runs out of commands to execute
or hits an END command, at which
point MMBasic will display the
command prompt (>) on the console
and wait for something to be entered
by the user.
A program consists of a number of statements or commands,
each of which causes the BASIC
interpreter to do something (the words
statement and command generally
mean the same and are used interchangeably in this tutorial).
Normally, each statement is on its
own line but you can have multiple
statements in the one line if you wish
with each separated by the colon character (:). For example:
a = 24.6 : PRINT a
Photo 3: the result of running the random lines example program. The start and
end positions of each line is chosen at random (using the RND function), as is
the colour used to draw the line. The background is dark blue.
generate a random integer in the range
of zero to 319 you would multiply the
result of the RND function by 320 and
then round it down.
This program is deceptively simple
but it will generate a kaleidoscope of
different coloured lines that fill the
screen with colour:
CLS RGB(0,0,128)
FOR nbr = 1 to 150
x1 = RND * 320
y1 = RND * 240
x2 = RND * 320
y2 = RND * 240
r = CINT(RND) * 255
g = CINT(RND) * 255
b = CINT(RND) * 255
LINE x1, y1, x2, y2, 1, RGB(r, g, b)
NEXT nbr
The program starts by using the CLS
command to clear the screen with a
dark blue colour and then it enters a
loop starting with the FOR command
and ending with the NEXT command.
The NBR variable is used to count
the number of times that the loop has
been executed and after 150 times,
the program will end. You can vary
the number of lines if you wish but
we found that 150 resulted in a nice
display.
Within the loop, the program calculates the various required parameters
(all of which are effectively random)
and then executes the LINE command
with these parameters.
68 Silicon Chip
Calculating the start and end coordinates is straightforward but generating the random colours requires some
explanation. Remember that the RND
function generates a random number
between zero and slightly less than
one.
The CINT() function will round
this fractional number either up or
down to an integer (a whole number
without a fraction). If the number is
less than 0.5 it will be rounded down
to zero, otherwise it will be rounded
up to one.
The result of CINT(RND) will then
be either a random zero or one. Multiplying this by 255 will give a number which is either zero or 255. Taking the red colour for example this
means that red will be off (number is
zero) or full on (number is 255). With
all three colours (red, green, blue)
being either full off or full on this will
generate the eight main colours (red,
yellow, cyan, etc) which results in a
vivid set of colours. See Photo 3 for
an example of the result of running
this program.
Program structure
So far we have been using small programs as our examples but before we
move onto larger programs we need
to cover some details of a BASIC program’s structure.
A BASIC program starts at the first
line and continues line by line until
Each line can start with a line number. Line numbers were mandatory in
the early BASIC interpreters, however,
modern implementations (such as
MMBasic) do not need them. You
can still use them if you wish but
they have no benefit and generally
just clutter up your programs. This
is an example of a program that uses
line numbers:
50 a = 24.6
60 PRINT a
GOTO command
BASIC has a number of constructs
that you can use to control the flow
of execution in a program. We have
covered IF...THEN...ELSE... and loops
using DO...LOOP or FOR...NEXT. Another method is the GOTO command.
This essentially tells MMBasic to jump
to another part of the program and
start executing from there. The target
of the GOTO can be a line number (as
explained above) or a label.
A label is an identifier that marks
part of the program. It must be the first
thing on the line and it must be terminated with the colon (:) character. The
label can be up to 32 characters long
and must follow the same rules for a
variable’s name. For example, in the
following, LoopBack is a label:
LoopBack: a = a + 1
When you use the GOTO command
to jump to that particular part of the
program, you would use the command
like this:
GOTO LoopBack
To put all this into context, the
siliconchip.com.au
following program will print out all
the numbers from 1 to 10:
z=0
LoopBack: z = z + 1
PRINT z
IF z < 10 THEN GOTO LoopBack
The program starts by setting the
variable z to zero then incrementing
it to 1 in the next line. The value of z
is printed and then tested to see if it
is less than 10. If it is less than 10 the
program execution will jump back to
the label LoopBack where the process
will repeat. Eventually the value of z
will be 10 and the program will run
off the end and terminate.
Of course, you could use a FOR loop
to do the same thing and it would be
simpler so this example is purely designed to illustrate what the GOTO
command can do.
In the past, the GOTO command developed a bad reputation. This is because if it is misused, a programmer
can write a program that continuously
jumps from one point to another (often
referred to as “spaghetti code”) and that
type of program is almost impossible
for another programmer to understand.
With constructs like the multi-line
IF statement and DO loops, the need
for the GOTO statement has been
reduced and it should be used only
when there is no other way of changing the program’s flow.
In fact, one of the more useful
instances where you may need GOTO
is for debugging or error handling with
the use of a label in a separate part of
the program.
Another potential valid use for
GOTO is to jump back to the start
of a DO or FOR loop without testing
the loop condition or incrementing
any variables, which is sometimes
necessary.
Comments
With all programs it’s a good idea to
provide comments and notes to help
anyone who has to later maintain or
modify the program. These should be
used to explain any non-obvious parts
of your program and generally inform
someone who is not familiar with the
program and what it is doing (remember that this could easily be you in a
few years’ time).
Comments are usually the first thing
that someone will read when they
pick up a program listing and extensive comments are regarded as one of
the hallmarks of a good programmer.
Having said that, some programmers believe that it’s more important
to write readable code than it is to add
comments extensively.
In MMBasic, a comment is any text
that follows the single quote character
(‘). Comments can be placed anywhere
in a program and when MMBasic sees
the comment character it will skip to
the end of the line and resume executing your program starting will the
following line. The following are some
examples:
‘ calculate the hypotenuse
PRINT SQR(a * a + b * b)
OR
INPUT var ‘ get the speed
That is all for this session. Next
month we will cover some more graphics programming including responding to touch on an touchscreen LCD
panel, drawing text and buttons, and
some advanced features such as data
SC
types and arrays.
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
Silicon Chip
Binders
REAL
VALUE
AT
$16.95
*
PLUS P
&
P
Are your copies of SILICON
CHIP getting damaged
or dog-eared just lying
around in a cupboard or
on a shelf? Can you quickly find a particular issue
that you need to refer to?
Keep your copies
safe, secure and
always available with
these handy binders
These binders will protect your
copies of SILICON CHIP. They
feature heavy-board covers,
hold 12 issues & will look great
on your bookshelf.
H 80mm internal width
H SILICON CHIP logo printed
in gold-coloured lettering on
spine & cover
Silicon Chip Publications
PO Box 139
Collaroy Beach 2097
Order online from www.
siliconchip.com.au/Shop/4
or call (02) 9939 3295 and
quote your credit card number. *See website for overseas prices.
March 2017 69
|