Silicon ChipGetting Started with the Micromite, Part Two - March 2017 SILICON CHIP
  1. Outer Front Cover
  2. Contents
  3. Publisher's Letter: Cutting-edge technology – in 1958
  4. Feature: Vale Maurie Findlay: Australian electronics “royalty” by Ross Tester
  5. Feature: Putting a big 43-inch 4K monitor to the test by Leo Simpson
  6. Feature: Australia’s largest vintage radio exhibition by Kevin Poulter
  7. Project: All-new Swimming Pool Lap Counter by John Clarke
  8. Project: The Stationmaster: walk-around PWM train control by Design by Bob Sherwood
  9. Project: Bargain Solar Cells – and what to do with them! by Ross Tester
  10. Product Showcase
  11. Serviceman's Log: Fixing a guitar amp is an enjoyable task by Dave Thompson
  12. Feature: Getting Started with the Micromite, Part Two by Geoff Graham
  13. Project: New SC200 Audio Amplifier - Part 3 by Nicholas Vinen
  14. Project: El Cheapo Modules, Part 5: LCD module with I²C by Jim Rowe
  15. Vintage Radio: Sony's TR-712 Mantel Radio by Ian Batty
  16. Subscriptions
  17. PartShop
  18. Market Centre
  19. Notes & Errata: GPS-Synchronised Analog Clock / Improved PICAXE Wireless Rain Alarm / High Power DC Motor Speed Control
  20. Advertising Index

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":
  • All-new Swimming Pool Lap Counter PCB [19102171] (AUD $15.00)
  • PIC16F88-I/P programmed for the All-new Swimming Pool Lap Counter [1910217A.HEX] (Programmed Microcontroller, AUD $15.00)
  • Hard-to-get parts for the LED Pool Lap Counter (Component, AUD $20.00)
  • Translucent blue UB1 lid for the All-new Swimming Pool Lap Counter (PCB, AUD $7.50)
  • Firmware (ASM and HEX) files for the Bright LED Pool Lap Counter [1910217A.HEX] (Software, Free)
  • All-new Swimming Pool Lap Counter PCB pattern (PDF download) [19102171] (Free)
  • All-new Swimming Pool Lap Counter front panel artwork (PDF download) (Free)
Items relevant to "The Stationmaster: walk-around PWM train control":
  • Stationmaster PWM train controller PCBs [09103171/2] (AUD $15.00)
  • Hard-to-get parts for the Stationmaster (Component, AUD $15.00)
  • Stationmaster PCB patterns (PDF download) [09103171/2] (Free)
  • Stationmaster panel artwork (PDF download) (Free)
Articles in this series:
  • Getting Started with the Micromite (February 2017)
  • Getting Started with the Micromite (February 2017)
  • Getting Started with the Micromite, Part Two (March 2017)
  • Getting Started with the Micromite, Part Two (March 2017)
  • Micromite Tutorial, Part 3: strings and arrays (May 2017)
  • Micromite Tutorial, Part 3: strings and arrays (May 2017)
  • Getting Started with the Micromite, Part 4 (June 2017)
  • Getting Started with the Micromite, Part 4 (June 2017)
Items relevant to "New SC200 Audio Amplifier - Part 3":
  • Ultra-LD Mk3/Mk4 Amplifier Power Supply PCB [01109111] (AUD $15.00)
  • New SC200 Audio Amplifier PCB [01108161] (AUD $10.00)
  • Hard-to-get parts for the SC200 Audio Amplifier Module (Component, AUD $50.00)
  • New SC200 Audio Amplifier PCB pattern (PDF download) [01108161] (Free)
Articles in this series:
  • New SC200 Audio Amplifier (January 2017)
  • New SC200 Audio Amplifier (January 2017)
  • New SC200 Audio Amplifier – Part 2 (February 2017)
  • New SC200 Audio Amplifier – Part 2 (February 2017)
  • New SC200 Audio Amplifier - Part 3 (March 2017)
  • New SC200 Audio Amplifier - Part 3 (March 2017)
Items relevant to "El Cheapo Modules, Part 5: LCD module with I²C":
  • 20x4 Alphanumeric serial (I²C) LCD module with blue backlight (Component, AUD $15.00)
  • 16x2 Alphanumeric serial (I²C) LCD module with blue backlight (Component, AUD $12.50)
  • Software for El Cheapo Modules: LCD module with I²C (Free)
Articles in this series:
  • El Cheapo Modules From Asia - Part 1 (October 2016)
  • El Cheapo Modules From Asia - Part 1 (October 2016)
  • El Cheapo Modules From Asia - Part 2 (December 2016)
  • El Cheapo Modules From Asia - Part 2 (December 2016)
  • El Cheapo Modules From Asia - Part 3 (January 2017)
  • El Cheapo Modules From Asia - Part 3 (January 2017)
  • El Cheapo Modules from Asia - Part 4 (February 2017)
  • El Cheapo Modules from Asia - Part 4 (February 2017)
  • El Cheapo Modules, Part 5: LCD module with I²C (March 2017)
  • El Cheapo Modules, Part 5: LCD module with I²C (March 2017)
  • El Cheapo Modules, Part 6: Direct Digital Synthesiser (April 2017)
  • El Cheapo Modules, Part 6: Direct Digital Synthesiser (April 2017)
  • El Cheapo Modules, Part 7: LED Matrix displays (June 2017)
  • El Cheapo Modules, Part 7: LED Matrix displays (June 2017)
  • El Cheapo Modules: Li-ion & LiPo Chargers (August 2017)
  • El Cheapo Modules: Li-ion & LiPo Chargers (August 2017)
  • El Cheapo modules Part 9: AD9850 DDS module (September 2017)
  • El Cheapo modules Part 9: AD9850 DDS module (September 2017)
  • El Cheapo Modules Part 10: GPS receivers (October 2017)
  • El Cheapo Modules Part 10: GPS receivers (October 2017)
  • El Cheapo Modules 11: Pressure/Temperature Sensors (December 2017)
  • El Cheapo Modules 11: Pressure/Temperature Sensors (December 2017)
  • El Cheapo Modules 12: 2.4GHz Wireless Data Modules (January 2018)
  • El Cheapo Modules 12: 2.4GHz Wireless Data Modules (January 2018)
  • El Cheapo Modules 13: sensing motion and moisture (February 2018)
  • El Cheapo Modules 13: sensing motion and moisture (February 2018)
  • El Cheapo Modules 14: Logarithmic RF Detector (March 2018)
  • El Cheapo Modules 14: Logarithmic RF Detector (March 2018)
  • El Cheapo Modules 16: 35-4400MHz frequency generator (May 2018)
  • El Cheapo Modules 16: 35-4400MHz frequency generator (May 2018)
  • El Cheapo Modules 17: 4GHz digital attenuator (June 2018)
  • El Cheapo Modules 17: 4GHz digital attenuator (June 2018)
  • El Cheapo: 500MHz frequency counter and preamp (July 2018)
  • El Cheapo: 500MHz frequency counter and preamp (July 2018)
  • El Cheapo modules Part 19 – Arduino NFC Shield (September 2018)
  • El Cheapo modules Part 19 – Arduino NFC Shield (September 2018)
  • El cheapo modules, part 20: two tiny compass modules (November 2018)
  • El cheapo modules, part 20: two tiny compass modules (November 2018)
  • El cheapo modules, part 21: stamp-sized audio player (December 2018)
  • El cheapo modules, part 21: stamp-sized audio player (December 2018)
  • El Cheapo Modules 22: Stepper Motor Drivers (February 2019)
  • El Cheapo Modules 22: Stepper Motor Drivers (February 2019)
  • El Cheapo Modules 23: Galvanic Skin Response (March 2019)
  • El Cheapo Modules 23: Galvanic Skin Response (March 2019)
  • El Cheapo Modules: Class D amplifier modules (May 2019)
  • El Cheapo Modules: Class D amplifier modules (May 2019)
  • El Cheapo Modules: Long Range (LoRa) Transceivers (June 2019)
  • El Cheapo Modules: Long Range (LoRa) Transceivers (June 2019)
  • El Cheapo Modules: AD584 Precision Voltage References (July 2019)
  • El Cheapo Modules: AD584 Precision Voltage References (July 2019)
  • Three I-O Expanders to give you more control! (November 2019)
  • Three I-O Expanders to give you more control! (November 2019)
  • El Cheapo modules: “Intelligent” 8x8 RGB LED Matrix (January 2020)
  • El Cheapo modules: “Intelligent” 8x8 RGB LED Matrix (January 2020)
  • El Cheapo modules: 8-channel USB Logic Analyser (February 2020)
  • El Cheapo modules: 8-channel USB Logic Analyser (February 2020)
  • New w-i-d-e-b-a-n-d RTL-SDR modules (May 2020)
  • New w-i-d-e-b-a-n-d RTL-SDR modules (May 2020)
  • New w-i-d-e-b-a-n-d RTL-SDR modules, Part 2 (June 2020)
  • New w-i-d-e-b-a-n-d RTL-SDR modules, Part 2 (June 2020)
  • El Cheapo Modules: Mini Digital Volt/Amp Panel Meters (December 2020)
  • El Cheapo Modules: Mini Digital Volt/Amp Panel Meters (December 2020)
  • El Cheapo Modules: Mini Digital AC Panel Meters (January 2021)
  • El Cheapo Modules: Mini Digital AC Panel Meters (January 2021)
  • El Cheapo Modules: LCR-T4 Digital Multi-Tester (February 2021)
  • El Cheapo Modules: LCR-T4 Digital Multi-Tester (February 2021)
  • El Cheapo Modules: USB-PD chargers (July 2021)
  • El Cheapo Modules: USB-PD chargers (July 2021)
  • El Cheapo Modules: USB-PD Triggers (August 2021)
  • El Cheapo Modules: USB-PD Triggers (August 2021)
  • El Cheapo Modules: 3.8GHz Digital Attenuator (October 2021)
  • El Cheapo Modules: 3.8GHz Digital Attenuator (October 2021)
  • El Cheapo Modules: 6GHz Digital Attenuator (November 2021)
  • El Cheapo Modules: 6GHz Digital Attenuator (November 2021)
  • El Cheapo Modules: 35MHz-4.4GHz Signal Generator (December 2021)
  • El Cheapo Modules: 35MHz-4.4GHz Signal Generator (December 2021)
  • El Cheapo Modules: LTDZ Spectrum Analyser (January 2022)
  • El Cheapo Modules: LTDZ Spectrum Analyser (January 2022)
  • Low-noise HF-UHF Amplifiers (February 2022)
  • Low-noise HF-UHF Amplifiers (February 2022)
  • A Gesture Recognition Module (March 2022)
  • A Gesture Recognition Module (March 2022)
  • Air Quality Sensors (May 2022)
  • Air Quality Sensors (May 2022)
  • MOS Air Quality Sensors (June 2022)
  • MOS Air Quality Sensors (June 2022)
  • PAS CO2 Air Quality Sensor (July 2022)
  • PAS CO2 Air Quality Sensor (July 2022)
  • Particulate Matter (PM) Sensors (November 2022)
  • Particulate Matter (PM) Sensors (November 2022)
  • Heart Rate Sensor Module (February 2023)
  • Heart Rate Sensor Module (February 2023)
  • UVM-30A UV Light Sensor (May 2023)
  • UVM-30A UV Light Sensor (May 2023)
  • VL6180X Rangefinding Module (July 2023)
  • VL6180X Rangefinding Module (July 2023)
  • pH Meter Module (September 2023)
  • pH Meter Module (September 2023)
  • 1.3in Monochrome OLED Display (October 2023)
  • 1.3in Monochrome OLED Display (October 2023)
  • 16-bit precision 4-input ADC (November 2023)
  • 16-bit precision 4-input ADC (November 2023)
  • 1-24V USB Power Supply (October 2024)
  • 1-24V USB Power Supply (October 2024)
  • 14-segment, 4-digit LED Display Modules (November 2024)
  • 0.91-inch OLED Screen (November 2024)
  • 0.91-inch OLED Screen (November 2024)
  • 14-segment, 4-digit LED Display Modules (November 2024)
  • The Quason VL6180X laser rangefinder module (January 2025)
  • TCS230 Colour Sensor (January 2025)
  • The Quason VL6180X laser rangefinder module (January 2025)
  • TCS230 Colour Sensor (January 2025)
  • Using Electronic Modules: 1-24V Adjustable USB Power Supply (February 2025)
  • Using Electronic Modules: 1-24V Adjustable USB Power Supply (February 2025)

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