Silicon ChipGetting Started with the Micromite, Part 4 - June 2017 SILICON CHIP
  1. Outer Front Cover
  2. Contents
  3. Publisher's Letter: SPICE streamlines circuit design
  4. Feature: The Flettner Rotating Sail and the Magnus Force by Ross Tester
  5. Project: All-new 10-Octave Stereo Graphic Equaliser, Part 1 by John Clarke
  6. Project: Arduino-based Digital Inductance & Capacitance Meter by Jim Rowe
  7. Feature: LTspice – simulating and circuit testing, Part 1 by Nicholas Vinen
  8. Serviceman's Log: Fixing the food processor that wouldn't by Dave Thompson
  9. Project: El Cheapo Modules, Part 7: LED Matrix displays by Jim Rowe
  10. Project: New Marine Ultrasonic Anti-Fouling Unit, Part 2 by Leo Simpson & John Clarke
  11. Feature: Getting Started with the Micromite, Part 4 by Geoff Graham
  12. Subscriptions
  13. Review: Keysight’s 9917A 18GHz Spectrum Analyser by Nicholas Vinen
  14. Product Showcase
  15. Vintage Radio: HMV’s 1951 portable model B61D by Associate Professor Graham Parslow
  16. PartShop
  17. Market Centre
  18. Advertising Index
  19. Notes & Errata: Micromite LCD BackPack V2 / ATmega-based Metal Detector with stepped frequency indication (Notebook Mar17)
  20. Outer Back Cover: Hare & Forbes Machineryhouse

This is only a preview of the June 2017 issue of Silicon Chip.

You can view 43 of the 112 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 10-Octave Stereo Graphic Equaliser, Part 1":
  • 10-Octave Stereo Graphic Equaliser PCB [01105171] (AUD $12.50)
  • Front panel for the 10-Octave Stereo Graphic Equaliser [01105172] RevB (PCB, AUD $15.00)
  • 10-Octave Stereo Graphic Equaliser acrylic case pieces (PCB, AUD $15.00)
  • 10-Octave Stereo Graphic Equaliser PCB pattern (PDF download) [01105171] (Free)
  • 10-Octave Stereo Graphic Equaliser front panel artwork (PDF download) (Free)
Articles in this series:
  • All-new 10-Octave Stereo Graphic Equaliser, Part 1 (June 2017)
  • All-new 10-Octave Stereo Graphic Equaliser, Part 1 (June 2017)
  • Completing our new Graphic Equaliser (July 2017)
  • Completing our new Graphic Equaliser (July 2017)
Items relevant to "Arduino-based Digital Inductance & Capacitance Meter":
  • 1nF ±1% polypropylene (MKP) or C0G/NP0 ceramic capacitor (Component, AUD $2.50)
  • 16x2 Alphanumeric serial (I²C) LCD module with blue backlight (Component, AUD $12.50)
  • Clear UB3 Lid for Arduino-based Digital LC Meter (PCB, AUD $5.00)
  • Firmware (Arduino Sketch) file for the Arduino-based Digital Inductance & Capacitance Meter [Arduino_LC_meter_sketch.HEX] (Software, Free)
  • Arduino-based Digital LC Meter front panel artwork (PDF download) (Free)
Items relevant to "LTspice – simulating and circuit testing, Part 1":
  • Software for the LTspice Tutorial, Part 1 (Free)
Articles in this series:
  • LTspice – simulating and circuit testing, Part 1 (June 2017)
  • LTspice – simulating and circuit testing, Part 1 (June 2017)
  • LTspice Part 2: Simulating and Testing Circuits (August 2017)
  • LTspice Part 2: Simulating and Testing Circuits (August 2017)
  • LTspice Tutorial Part 3: Modelling an NTC Thermistor (September 2017)
  • LTspice Tutorial Part 3: Modelling an NTC Thermistor (September 2017)
  • LTspice Simulation: Analysing/Optimising Audio Circuits (May 2018)
  • LTspice Simulation: Analysing/Optimising Audio Circuits (May 2018)
Items relevant to "El Cheapo Modules, Part 7: LED Matrix displays":
  • MAX7219 controller (SMD) with pluggable 8x8 red LED matrix display (Component, AUD $4.50)
  • MAX7219 controller (DIP) with pluggable 8x8 red LED matrix display and jumper leads (Component, AUD $2.50)
  • MAX7219 controller (SMD) with red 8-digit 7-segment display (Component, AUD $5.00)
  • Software for MAX7219 (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)
Items relevant to "New Marine Ultrasonic Anti-Fouling Unit, Part 2":
  • New Marine Ultrasonic Anti-Fouling Unit PCB [04104171] (AUD $15.00)
  • PIC16F88-I/P programmed for the New Marine Ultrasonic Anti-Fouling Unit [0410417A.HEX] (Programmed Microcontroller, AUD $15.00)
  • One 40kHz 50W ultrasonic transducer (Component, AUD $55.00)
  • ETD29 transformer components (AUD $15.00)
  • IPP80N06S4L-07 high-current N-channel Mosfet (TO-220) (Component, AUD $2.00)
  • New Marine Ultrasonic Anti-fouling unit lid panel artwork (PDF download) (Free)
Articles in this series:
  • New Marine Ultrasonic Anti-Fouling Unit (May 2017)
  • New Marine Ultrasonic Anti-Fouling Unit (May 2017)
  • New Marine Ultrasonic Anti-Fouling Unit, Part 2 (June 2017)
  • New Marine Ultrasonic Anti-Fouling Unit, Part 2 (June 2017)
Items relevant to "Getting Started with the Micromite, Part 4":
  • Software for the Micromite Tutorial, Part 4 (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)

Purchase a printed copy of this issue for $10.00.

Getting Started with the Micromite T he Micromite is intended to be used primarily as an “embedded controller”. This is the situation where the processor is running a dedicated program to control external circuitry. To help in this role, the Micromite has a number of built-in features such as the ability to balance performance and power consumption, to automatically recover from errors and so on. Using the CPU command, your program can instantly speed up or slow down the processor and, because the power consumption of the Micromite is related to the processor speed, you can balance speed against power consumption. This is particularly important in battery-powered applications. The command looks like this: CPU <speed in MHz> The speed can be any one of 48, 40, 30, 20, 10 or 5. For example, “CPU 5” will set the speed to 5MHz with a current consumption of about 6mA (for the Micromite alone) while “CPU 48” will set it to 48MHz and it will draw about 30mA. The default is 40MHz and the speed can be changed at any time so you can speed up for a few lines in a critical part of the program, then drop back to a slower speed to conserve power. You can further conserve power by sending the Micromite to sleep with the CPU SLEEP command. In this mode, all processing will stop and 78  Silicon Chip the current consumption will drop to about 40µA. The Micromite can wake up after a specified number of seconds or it can be woken by a change of level on the pin designated as the WAKEUP pin (pin 16 on the 28-pin Micromite). Note that if you are using the LCD BackPack, the display will continue to consume power (much more than 40µA). If you have software control over the backlight, as in the Plus BackPack or BackPack V2, you should turn it off before executing CPU SLEEP to save power and turn it back on after wake-up. Saving data Because the Micromite usually does not have a normal storage system (such as an SD card), it needs to have a facility to save some data so it can be recovered when power is restored. This might be calibration data, user options, the current state, etc. This can be done with the VAR SAVE command which will save the variables listed on its command line in non-volatile flash memory. For example: VAR SAVE ConfigX, ConfigY On power-up, these variables can be restored with the VAR RESTORE command which adds all the saved variables to the variable table of the running program. Normally, this command is placed near the start of a program so that the variables are ready for immediate use. Using this feature, a typical program would look like this: VAR RESTORE ' any saved variables are restored ‘ <rest of the program continues> ' save the variables if they have changed IF ConfigurationChanged THEN VAR SAVE Config1, Config2 The VAR RESTORE command at the start of the program will try to restore any (and all) saved variables. If none have been saved, the command will do nothing. Later, the program saves the variables Config1 or Config2 if they have been changed and then, when the program is re-started, the VAR RESTORE command will find and automatically restore them. Interrupts An interrupt is some event that "interrupts" the main program and causes MMBasic to temporarily execute some other code. Interrupts are a handy way of dealing with an event that can occur at an unpredictable time, for example, when an input connected to a limit switch has gone high. In your program, you could continuously check to see if the input has changed state but an interrupt makes for a more cleaner and readable siliconchip.com.au Part 4: by Geoff Graham If you have been following this tutorial, you should be at the stage where you can now write your own programs for the Micromite. But there are a few more specialised features of the Micromite that we need to cover before you graduate. These include power saving, using touch-sensitive LCD panels and handling button presses, storing data in non-volatile memory, interrupt routines and other embedded controller features. program (and possibly a faster response to external events). Here is a practical example: SETPIN 5, INTH, MyIntSub DO ‘ <main program> LOOP SUB MyIntSub PRINT "Input has gone high" END SUB The program starts by configuring pin 5 as an interrupt source that will trigger an interrupt when the voltage on the pin goes high (ie, INTH). You can also trigger an interrupt when the voltage goes low (INTL) or when it changes both from low to high or high to low (INTB). The last parameter is the name of the subroutine to execute when the interrupt occurs – this is just an ordinary subroutine. When an interrupt occurs, MMBasic will temporarily stop running the main program and execute the code in the interrupt subroutine. Then, when the execution of the subroutine has finished, MMBasic will return to executing the main program at the exact point where it was originally interrupted. The main program will carry on as normal. In the above example, the subroutine would just display a message on the console but you can do anything you wish. For example, you could sigsiliconchip.com.au nal an alarm, reverse the direction of a motor, etc. You can set an interrupt on any I/O pin and you can have up to ten I/O pins simultaneously operating as interrupts, each with its own interrupt subroutine or, if you wish, sharing one or more subroutines. If two interrupts occur simultaneously, MMBasic will execute the subroutine associated with the interrupt that was defined first, then when it has finished (and if the next interrupt condition still exists) it will execute the next interrupt subroutine, and so on. While MMBasic is executing the interrupt subroutine, all other interrupts are ignored. This means that if your interrupt code takes too long to execute there is a chance that another interrupt (such as a button press) might arise and vanish while your first interrupt subroutine is still executing. This would cause the new interrupt to be missed; for this reason, interrupt subroutines should be as short as possible. Many other parts of MMBasic can also generate interrupts. For example, you can specify an interrupt that repeats with a specified number of milliseconds between each interrupt (the tick timer); or you can have an interrupt when an infrared remote control signal is received or when a certain number of bytes has been received on a serial interface. Normally, MMBasic will respond to a single interrupt within 100µs so you can use interrupts to catch reasonably brief events. For example, ignition pulses in a petrol engine. Keeping time In the Micromite, there are many ways that a program can track the time including an internal clock/calendar, a millisecond timer, timed interrupts and the PAUSE command. The current date and time can be accessed using the special identifiers DATE$ and TIME$ which act like pre-defined variables. These are reset to midnight on the 1st January 2000 at power-up so you need to set the current date and time before you can use them. This is done by assigning the current date/time (as strings) to these variables. For example, the following will set the Micromite's clock to 4:25PM on May 7th: DATE$ = "7/03/2017" TIME$ = "16:25" You can also use the RTC command to automatically set the correct time from an external Real Time Clock (RTC) on power-up and then the Micromite's internal clock will always be correct. Both DATE$ and TIME$ return their value as a string which you can then pull apart using specific string June 2017  79 Silicon Chip Binders REAL VALUE AT $16.95 * PLUS P & P functions (or just use it as a string). As an example, if you entered this at the command prompt: PRINT DATE$, TIME$ You could expect to see something like this: 7/08/2017 16:25:51 TIMER is another special variable which returns the number of milliseconds since being reset to zero (it is also reset when the Micromite is powered up). You can use it to measure the time difference between two events as shown in the following example: TIMER = 0 ‘ <timed code> PRINT TIMER "ms" 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. 80  Silicon Chip Sometimes, after sending a control signal to a device, you might be required to wait for a defined number of milliseconds before you can send the next control signal. The PAUSE command is perfect for this type of job and we have used it a number of times in past instalments of this tutorial – it will simply pause the execution of the program for a certain number of milliseconds. MMBasic also allows you to set up to four "tick" timers. Each acts like the tick of a clock and on each tick, MMBasic will execute an interrupt subroutine specified in the command. The tick times are specified in milliseconds and can range from a few milliseconds to many days. For example, the following code fragment will print the current time and the voltage on pin 5 every second. This process will run independently of the main program which could be doing something completely unrelated. SETPIN 5, AIN SETTICK 1000, TickInt DO ‘ <main processing loop> LOOP SUB TickInt ‘ tick interrupt PRINT TIME$, PIN(5) END SUB The second line sets up the "tick" interrupt, the first parameter of SETTICK is the period of the interrupt (1000ms) and the second is the interrupt subroutine which will be executed on every "tick". Every second (ie, 1000ms), the main process- ing loop will be interrupted and the subroutine TickInt will be executed. Watchdog timer When the Micromite is running as an embedded processor, it will generally not have anything connected to the console and it will automatically start running its program when the OPTION AUTORUN ON command has been used. This is fine, however, there is always the possibility that a fault in the program could cause MMBasic to generate an error and return to the command prompt. Another possibility is that the BASIC program could get itself stuck in an endless loop for some reason. In either case, the effect to the user of the device would be the same; the Micromite would stop doing its programmed job until the power was cycled. To guard against this, the watchdog timer can be used. This is a timer that counts down towards zero and when it reaches zero, the processor is automatically restarted (the same as when power was first applied), even if MMBasic was sitting at the command prompt. The WATCHDOG command specifies how many milliseconds are allowed before the reset. For example, the following will set the watchdog timer to 200 milliseconds: WATCHDOG 200 Normally, this command will be placed in strategic locations in the program to keep resetting the timer and therefore preventing it from counting down to zero. Then, if a fault occurs, the timer will not be reset, it will reach zero and the program will be restarted (assuming that AUTORUN is set). To give a practical example, the following program will display the temperature in the centre of an attached LCD display once a second (the TEMP() function returns the temperature from a DS18B20 temperature sensor): DO TEXT 160, 120, STR$(TEMPR(4)), CM, 1, 2 PAUSE 1000 LOOP There is very little to go wrong with such a simple program but just suppose that the memory of the Micromite could be hit by a stray cosmic siliconchip.com.au ray that upset the program causing it to halt with some error. To protect against this you can add the WATCHDOG command as follows: DO WATCHDOG 2000 TEXT 160, 120, STR$(TEMPR(4)), CM, 1, 2 PAUSE 1000 LOOP Every time through the loop, the WATCHDOG command would reset the watchdog timer to two seconds, then the rest of the loop would take a bit over a second to complete before repeating so the watchdog timer will never get the opportunity to reach zero. But, if the stray cosmic ray did hit and stopped the program, the watchdog timer would continue counting down until it hit zero – at which point the Micromite would be automatically restarted, the program would recommence displaying the temperature and more importantly, the user would only see a momentary glitch. Handling touch As well as driving an LCD panel to display graphics and text, the Micromite can respond to touch on the display's screen. Touch-sensitive panels have a transparent resistive membrane over the LCD screen and when this is touched, the resistance of the membrane changes and the controller on the panel will send a signal (the IRQ signal) to the Micromite, to indicate this event. The controller will also calculate the position of the touch and MMBasic queries the controller to get this information. Within your program, it is easy to get the touch position; the MMBasic function calls TOUCH(X) and TOUCH(Y) report the current touch coordinates in pixels. Note that the X and Y used in the touch function are keywords, not variables. If the screen is not being touched, both TOUCH(X) and TOUCH(Y) will return negative one (-1). As a simple example, the following program will display the coordinates of the current touch location on the console. Because the program runs in a tight loop, the readings will quickly scroll off the top of the terminal emulator's screen but as you touch the screen you can see the precise location: DO PRINT TOUCH(X), TOUCH(Y) LOOP Screenshot 1 provides an example of this program at the instance that the screen was touched. You can see how the TOUCH() function was returning -1 until a touch was detected then it returned the coordinates of the touch. Adding touch input can make a big difference to a project. It can be used to eliminate inefficient knobs and switches and it allows the designer to implement many more configuration options than would have previously been practical. The touch system can be very simple (eg, touch anywhere on the screen to proceed) or it could be complex with the screen covered in checkboxes and buttons. The most common requirement is to display one or more buttons on the screen which act like real buttons, ie, when touched the image of the button changes to show that it is selected and when released it returns to its previous appearance. In this final section of our tutorial, we will describe one way of implementing this feature. This example also serves to illustrate some of the more advanced aspects of Micromite programming. Drawing a button To start, we need a subroutine to draw a button. The following will draw a button with rounded corners and some text positioned in the centre: SUB Button x, y, txt$, fc% LOCAL w = MM.FONTWIDTH * (LEN(txt$) + 1) LOCAL h = MM.FONTHEIGHT * 2 RBOX x, y, w, h, , fc% TEXT x + w / 2, y + h / 2, txt$, CM, , , fc% END SUB The arguments x and y are the coordinates of the top-left corner of the button, txt$ is the text to display in the centre of the button and fc is the colour to use for the button. Within the subroutine, we first calculate the width and height of the required box based on the text to be used as the caption. MM.FONTWIDTH and MM.FONTHEIGHT are read-only Screenshot 1 (left): this screen capture provides an example of the simple touch demonstration program caught at the instance that the screen was touched. You can see how the TOUCH() function was returning -1 until a touch was detected then it returned the coordinates of the touch. Screenshot 2 (right): this is what the simple button looks like. The subroutine calculated the dimensions of the box to fit around its caption then, using these dimensions, drew a rounded box and centrally positioned the text inside the box. siliconchip.com.au June 2017  81 variables that are automatically set by MMBasic to the dimensions of the current font and LEN() is a function that returns the length of a string in characters. Note that we are both declaring w and h as local variables and setting their value in the one statement. Also, note that we add to the text's dimensions so that the surrounding box has room for the text. Using these dimensions, we then draw a rounded box and centrally position the text inside the box. Voilà! We have created a button. As an example of using the above subroutine, having already defined it, the following will draw a cyan button: FONT #1, 2 CLS Button 100, 100, "Hello", RGB(cyan) The default font (font #1) is rather small so we use the FONT command to set the default to double size. Screenshot 2 shows what the result looks like. Detecting touch It would be useful if we could also tell if this button has been touched. FONT #1, 2 CLS SETPIN 4, DOUT SETPIN 15, INTB, BtnInt BtnInt To do this, we can modify the subroutine to check if the current touch coordinates are within the bounds of the button. We also need to convert the subroutine into a function so that it can return a value indicating that the button is indeed being touched. So our new function looks like this: FUNCTION Button(x, y, txt$, fc%) LOCAL w = MM.FONTWIDTH * (LEN(txt$) + 1) LOCAL h = MM.FONTHEIGHT * 2 LOCAL tx = TOUCH(X) LOCAL ty = TOUCH(Y) IF tx >= x AND tx <= x + w AND ty >= y AND ty <= y + h THEN Button = 1 RBOX x, y, w, h, , fc% TEXT x + w / 2, y + h / 2, txt$, CM, , , fc% END FUNCTION This is similar to the previous subroutine in that it first calculates the width and height of the box and draws the button. It also gets the X and Y coordinates of the current touch point and saves them in the local variables tx and ty. We do this because it makes Handy Tip 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. DO ‘ <program code> LOOP SUB BtnInt IF Button(115, 50, “START”, RGB(red)) THEN PIN(4) = 1 IF Button(122, 150, “STOP”, RGB(green)) THEN PIN(4) = 0 END SUB FUNCTION Button(x, y, txt$, fc%) LOCAL w = MM.FONTWIDTH * (LEN(txt$) + 1) LOCAL h = MM.FONTHEIGHT * 2 LOCAL tx = TOUCH(X) LOCAL ty = TOUCH(Y) IF tx >= x AND tx <= x + w AND ty >= y AND ty <= y + h THEN Button = 1 RBOX x, y, w, h, , fc%, fc% TEXT x + w / 2, y + h / 2, txt$, CM, , , RGB(black), fc% ELSE RBOX x, y, w, h, , fc%, RGB(black) TEXT x + w / 2, y + h / 2, txt$, CM, , , fc% ENDIF END FUNCTION Fig.1: this program can be used to draw buttons on the LCD screen and also detect if either has been pressed and highlight it, as shown in Screenshots 3-5. 82  Silicon Chip the following IF statement less complex and easier to understand. The IF statement then checks if the current touch coordinates are within the box and sets the value of the function to one (ie, true) if it is. Note that we do not bother setting the value of the function to zero if the touch is outside the box because this is the default value returned by a function. Also note that if the user is not touching the screen, the function will still return false because the values returned for the X and Y touch values will be -1, which are outside of the button's area. This function can then be used to easily check if the button has been touched. For example: FONT #1, 2 CLS DO IF Button(100, 100, "Hello", RGB(cyan)) THEN PRINT "Button touched" LOOP Note that this program will continuously redraw the button on the screen; this is not a problem because the redraw is very fast and, as the image of the button is not changing, the user will not see any flicker or change in the image. However, it is useful to give the user an indication that the button is indeed touched and one good way to do this is to display the button in reverse video. This is easy to do, as shown in this further improved version of the Button function: FUNCTION Button(x, y, txt$, fc%) LOCAL w = MM.FONTWIDTH * (LEN(txt$) + 1) LOCAL h = MM.FONTHEIGHT * 2 LOCAL tx = TOUCH(X) LOCAL ty = TOUCH(Y) IF tx >= x AND tx <= x + w AND ty >= y AND ty <= y + h THEN Button = 1 RBOX x, y, w, h, , fc%, fc% TEXT x + w / 2, y + h / 2, txt$, CM, , , RGB(black), fc% ELSE RBOX x, y, w, h, , fc%, RGB(black) TEXT x + w / 2, y + h / 2, txt$, CM, , , fc% ENDIF END FUNCTION We are now drawing the button with the foreground and background colours reversed if touch is detected, siliconchip.com.au otherwise, the button is drawn normally. If you use this new version in the continuous loop example given above, you will see that the effect of touching the button is obvious to the user. Sharp-eyed readers will notice that we are now filling the rounded box of our button with a colour (either the colour of the button or black) and because we do that, the button now appears to flicker as it is redrawn quickly. This will not be a problem because in the next section we will only redraw the button on a touch (not continuously) so the flicker will be hardly noticeable. Touch interrupt handling The above method of detecting touch works well but a program usually cannot just sit there spinning around waiting for a button to be touched. It will have other duties to attend to, like getting data from a sensor and reacting to it. The other factor is that you, as the programmer, cannot predict when the user is going to touch the button. From our earlier discussion on interrupts, you might have already guessed by now that this is a perfect job for an interrupt as these are intended for situations where you need to respond to unpredictable events. What we can do is set up an interrupt on the touch IRQ signal input (generated by the LCD panel when it is touched). If you recall our earlier articles, this signal will go low when the screen is touched and then revert to high when it is lifted. The I/O pin used for this signal was defined in the OPTION LCDPANEL command when you first configured the Micromite to work with the panel. On the Micromite LCD BackPack (V1 and V2), this is pin 15 and we will use this in our example. Because we want to know when the touch is applied or removed, we set the interrupt to work on both high-to-low and low-to-high transitions as follows (BtnInt is the subroutine to call on the interrupt): SETPIN 15, INTB, BtnInt Now, say that we want to control a motor with two buttons on the screen; the first should be labelled START and coloured red and the second is STOP and is coloured green. When the user touches START, the program should set pin 4 high (presumably this is driving a relay consiliconchip.com.au Screenshots 3, 4 and 5: this is what our motor control buttons look like on the LCD screen. The first shows both buttons as they initially appear while the next two screen captures show the result of touching the start button and the stop button. June 2017  83 trolling power to the motor) and when the user touches STOP, that pin should be set to low again. Fig.1 contains the full program, including the Button function. You can copy or type it into a Micromite (or download it from the Silicon Chip website) and with a suitable display it will run "as is". It uses an interrupt to detect when the user has touched a button and calls the function Button to handle the buttons: This might look a little daunting so we will go through the new program code line by line. First, we set the font, then CLS is used to clear the screen and pin 4 is configured as an output (this is controlling our motor). Next, the SETPIN command configures an interrupt on the touch IRQ signal (pin 15). INTB specifies that the interrupt will occur on either transition of this signal and BtnInt is the subroutine to call when that transition occurs. We then call the interrupt subroutine itself. This is perfectly legitimate as an interrupt subroutine is just a normal subroutine. The reason for doing this is to draw the buttons on the screen initially. After this, the program enters an endless loop where it could be doing things like monitoring input signals and sensors and reacting accordingly. The interrupt subroutine (BtnInt) is quite simple. It first checks if the START button has been pressed and if so will set the motor (pin 4) to run. Then it checks the STOP button, and if touched, stops the motor. When we first called this subroutine (just after the clear screen command), there was presumably no touch on the screen so this run through would simply draw the buttons in their normal states (remember that the Button function draws the button as well as checking if it is touched). Now, if the user touches the START button, the interrupt will be triggered, the Button function will detect that the touch is within the button and it will redraw the button in reverse video. The function will also return true to the IF statement in the BtnInt subroutine, causing pin 4 to be set high and run the motor. When the user removes the touch, the interrupt subroutine will be called a second time and because no button is touched, the Button function will redraw all buttons in their normal 84  Silicon Chip state. Similarly, when the user touches the STOP button, it will be displayed in reverse video and pin 4 will be set low to stop the motor. That is it! There is nothing more that you need to do. Screenshot 3 shows both buttons as they initially appear while Screenshots 4 and 5 show the result of touching the START button and the STOP button respectively. You can extend this to as many buttons as you want. For example, you could draw a numeric keypad on the screen so that the user could enter a number. You can also write a different subroutine to draw and monitor a checkbox (you could call it CheckBox), or radio buttons (similar to checkboxes but where only one can be selected at a time), or whatever. You could also switch between different screens full of different objects by clearing the screen (using CLS) then redefining the touch interrupt to point to a different subroutine which implements the new set of objects. Note that the Micromite Plus uses a different method of defining a touch interrupt and it incorporates commands to generate and automatically manage screen objects like buttons for you. So the Micromite Plus is much easier to work with and the above code is not necessary if you are using this advanced version of the Micromite. Other Features In this tutorial series, we have taken you from the simple features of the Micromite such as setting an output high or low, through programming in MMBasic including expressions, subroutines and functions and on to complex features like displaying graphics on an LCD screen and responding to touch. However, the Micromite incorpo- rates many more advanced features that are simply too complex to cover in a tutorial like this. The Micromite User Manual (which can be downloaded from the Silicon Chip website) goes into the detail of how to use these features but in summary, they are: • The ability to interface to common external sensors for temperature, humidity and distance plus the ability to control mechanical servos and devices that need an analog signal (the PWM command). • The Micromite can receive and send infrared remote control signals enabling you to add remote control to your creation using a common IR remote control. • Support for an extensive range of communications protocols which will allow you to connect to and communicate with test equipment, WiFi modules, GPS receivers and a wide range of sensors for anything from acceleration through to atmospheric pollution. • Graphical controls on the Micromite Plus which include on-screen buttons, switches, checkboxes, radio buttons and more. Each of these can be defined with a single command and from then on MMBasic will manage the object including animating it when the user touches it. • The ability to customise MMBasic by adding your own commands, functions and fonts to the language (the DEFINEFONT and LIBRARY commands). • The ability to add to MMBasic commands and functions written in the C programming language or MIPS assembler. These allow you to exploit the full speed and features of the PIC32 processor while still using the easy to program BASIC language for the rest of your program. SC Information and help 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). New versions of the MMBasic firmware and programming examples are also uploaded to the author’s website. A good place to find help is the Back Shed forum (www.thebackshed. com/forum/forum_topics.asp?FID=16) where there are many enthusiastic Maximite and Micromite users who would be only too happy to offer advice. siliconchip.com.au