Micromite Manual
Micromite Manual
Micromite Manual
User Manual
MMBasic Ver 4.6b
Contents
Introduction............................................................................................................................. 3
Suitable Microcontrollers ........................................................................................................ 4
28-pin Micromite Connections ................................................................................................ 6
44-pin Micromite Connections ................................................................................................ 7
Quick Start Tutorial................................................................................................................. 8
Using MMBasic..................................................................................................................... 11
Micromite Special Features .................................................................................................. 13
Special Hardware Devices ................................................................................................... 16
Full Screen Editor ................................................................................................................. 24
Defining and Using Variables ............................................................................................... 26
Using the I/O pins................................................................................................................. 29
Timing................................................................................................................................... 32
Defined Subroutines and Functions...................................................................................... 33
Electrical Characteristics ...................................................................................................... 37
MMBasic Characteristics ...................................................................................................... 38
Predefined Read Only Variables .......................................................................................... 40
Commands ........................................................................................................................... 41
Functions.............................................................................................................................. 60
Obsolete Commands and Functions .................................................................................... 66
Appendix A Serial Communications .................................................................................. 67
Appendix B I2C Communications...................................................................................... 71
Appendix C 1-Wire Communications................................................................................. 77
Appendix D SPI Communications...................................................................................... 78
Page 2
Introduction
The Micromite MkII is a Microchip PIC32MX170F256 microcontroller
programmed with the MMBasic firmware. This chip is available in an easy
to use 28-pin dual in line package which can be easily soldered and plugged
into an IC socket. Even better, it costs just $4.
MMBasic is a Microsoft BASIC compatible implementation of the BASIC
language with floating point and string variables, arrays, long variable
names, a built in program editor and many other features.
Using MMBasic you can use communications protocols such as I2C or SPI
to get data from a variety of sensors. You can measure voltages, detect
digital inputs and drive output pins to turn on lights, relays, etc. All from
inside this cheap 28-pin chip.
Everything is internal to the Micromite and it will run from a couple of AA batteries. The only extra
component required is a 47F capacitor.
In summary the features of the Micromite MkII are:
A fast 32 bit CPU with 256K of flash and 64K RAM running a powerful BASIC interpreter. 60KB of
non volatile flash memory is reserved for the program, 52KB of RAM is available for BASIC variables,
arrays, buffers, etc. This is sufficient for quite large BASIC programs up to 2500 lines or more.
The BASIC interpreter is full featured with floating point, 64-bit integers and string variables, long
variable names, arrays of floats, integers or strings with multiple dimensions, extensive string handling
and user defined subroutines and functions. Typically it will execute a program at 30,000 lines per
second.
Nineteen input/output pins are available on the 28-pin chip. These can be independently configured as
digital input or output, analog input, frequency or period measurement and counting. Ten of the pins can
be used to measure voltages and another seven can be used to interface with 5V systems. MMBasic can
also be installed on the 44-pin version of the chip providing 33 input/output pins.
Programming and control is done via a serial console (TTL voltage levels) at 38400 baud (configurable).
Once the program has been written and debugged the Micromite can be instructed to automatically run the
program on power up with no user intervention. Special software is not needed to develop programs.
A full screen editor is built into the Micromite. This only requires a VT100 terminal emulator and can
edit the whole program in one session. It includes advanced features such as search and copy, cut and
paste to and from a clipboard.
Easy transfer of programs from another computer (Windows, Mac or Linux) using the XModem
protocol or by streaming the program over the serial console input.
Input/Output functions in MMBasic will generate pulses (both positive and negative going) that will
run in the background while the program is running. Other functions include timing (with 1 mS
resolution), BASIC interrupts generated on any change on an input pin and an internal real time clock.
The Micromite has built in commands to directly interface with infrared remote controls, the DS18B20
temperature sensor, LCD display modules, battery backed clock and numeric keypads.
Up to five PWM or SERVO outputs can be used to create various sounds, control servos or generate
computer controlled voltages for driving equipment that uses an analogue input (eg, motor controllers).
Special embedded controller features in MMBasic allow the clock speed to be varied to balance power
consumption and speed. The CPU can also be put to sleep with a standby current of just 90A. While in
sleep the program state and all variables are preserved. A watchdog feature will monitor the running
program and can be used to restart the processor if the program fails with an error or is stuck in a loop.
The running program can be protected by a PIN number which will prevent an intruder from listing
or modifying the program or changing any features of MMBasic.
Page 3
Suitable Microcontrollers
The Micromite MkII firmware will run on all variants of the PIC32MX170F256 microcontroller, in both 28-pin and
44-pin packages. These are available from Microchip (http://www.microchipdirect.com) or their distributors
use Octopart (http://octopart.com) to search for suppliers.
28-pin Chips
The best chip to use is the PIC32MX170F256B-50I/SP which is guaranteed to run up to 48MHz (the maximum
Micromite speed) and is in a 28-pin DIL package. It costs about $4 direct from Microchip. There is a 40MHz
variant (the PIC32MX170F256B-I/SP) which is a little cheaper. All of the 40MHz chips tested have run fine at
48MHz so this chip is also a good option.
The following is a summary of the recommended chips for the Micromite MkII in a 28-pin package:
PIC32MX170F256B-50I/SP
PIC32MX170F256B-50I/SO
PIC32MX170F256B-I/SP
Should run at 48MHz despite its 40MHz spec. 28-pin DIL package.
PIC32MX170F256B-I/SO
The firmware will also run on the PIC32MX270F256 series of chips. These have built in USB (which is not
supported in the Micromite) and therefore you lose access to two I/O pins (pins 15 and 23) which are used in
the chip for dedicated USB functions. In addition pins 21 and 22 are not 5V tolerant.
PICKit 3
Connector
1 - MCLR
2 - Vcc
3 - GND
4 - PGD
5 - PGC
6 - NC
1
10K
28
27
4
5
8
20
+
19
47F 6V
Ceramic or
Tantalum
13
Page 4
44-pin Chips
The PIC32MX170F256 is also available in a 44-pin surface mount package which provides a lot more I/O pins
(a total of 33 in MMBasic).
The best chip to use is the PIC32MX170F256D-50I/PT which is guaranteed to run up to 48MHz and costs a
little over $4 when purchased from Microchip. Similar to the 28-pin package there are versions rated at
40MHz and versions that support USB - with the latter you lose access to two I/O pins which are reserved for
USB functions (pins 10 and 42).
The following is a summary of the recommended chips for the Micromite in a 44-pin package:
PIC32MX170F256D-50I/PT
PIC32MX170F256DI/PT
These chips are in a TQFP surface mount package which has a lead pitch of 0.8mm. This is reasonably easy to
solder and the chip can be mounted on a carrier board (for example futurlec.com part code 44PINTQFP) which
brings the pins out on an easy to use 0.1 inch grid. Another excellent choice is the 44-pin Micromite module
from micromite.org which includes a USB to serial converter and pre programmed microcontroller.
The Micromite MkII firmware file will work with either the 28 or 44-pin chips. The only difference is that the
44-pin chip has an extra fourteen I/O pins that are accessible from within MMBasic.
The power requirements and the need for a 47F capacitor are exactly the same as for the 28-pin chip.
Loading the Micromite firmware is done via a PIC32 programmer using the following circuit.
geoffg.net/programming_pics.html for a tutorial on programming PIC chips.
See
2.3 to 3.6V
26mA
PICKit 3
Connector
1 - MCLR
2 - Vcc
3 - GND
4 - PGD
5 - PGC
6 - NC
17 28
40
18
10K
7
21
22
47F 6V
Ceramic or
Tantalum
6 16 29 39
Page 5
23 ANALOG | DIGITAL
The notation is as follows (the mnemonic in brackets is the mode used in the SETPIN command):
ANALOG
These pins can be used to measure voltage (AIN).
DIGITAL
Can be used for digital I/O such as digital input (DIN), digital output (DOUT) and open
collector output (OOUT).
INT
Can be used to generate an interrupt (INTH, INTL and INTB).
COUNT
Can be used to measure frequency (FIN), period (PIN) or counting (CIN).
5V
These pins can be connected to 5V circuits. All other I/O pins are strictly 3.3V maximum.
COM xxx
These are used for serial communications (see Appendix A)
I2C xxx
These are used for I2C communications (see Appendix B)
SPI xxx
If SPI is enabled these pins will be used for SPI I/O (see Appendix D)
PWM xxx
PWM or SERVO output (see the PWM and SERVO commands)
IR
This can be used to receive signals from an infrared remote control (see the IR command)
WAKEUP
This pin can be used to wake the CPU from a sleep (see the CPU SLEEP command).
Pins 27 and 28 are the ground and power for analog measurements. Normally they are connected to the general
ground and power (pins 8 and 13) but if you require noise free and accurate analog readings you should make
sure that the power on pin 28 is regulated to 3.3V and well filtered. Also your analog inputs should be
referenced to pin 27 (the analog ground).
Within MMBasic the SETPIN command is used to set the function of an I/O pin for general I/O. The PIN
command or function is then used to interact with the pin. For example, this will print out the voltage on pin 7:
SETPIN 7, AIN
PRINT "The voltage is" PIN(7) "V"
This voltage reading is referenced to pin 28 and assumes that the supply voltage on this pin is exactly 3.3V.
You will need to scale the readings in your BASIC program if you use a supply voltage other than this.
Micromite MkII User Manual
Page 6
Pin 34
Pin 12
Pin 1
Pin
23
Pin
22 PWM 1B | DIGITAL | ANALOG
21 PWM 1A | DIGITAL | ANALOG
ANALOG | DIGITAL 25
ANALOG | DIGITAL 26
19 DIGITAL | ANALOG
ANALOG | DIGITAL 27
28
GROUND 29
DIGITAL | COM2: TRANSMIT
30
33
12 5V | DIGITAL
34
DIGITAL | 5V 35
DIGITAL 36
DIGITAL | 5V 37
DIGITAL | 5V 38
GROUND 39
POWER (+2.3 to +3.6V)
6 GROUND
40
5 5V | INT | DIGITAL
4 5V | INT | DIGITAL
DIGITAL | 5V | COUNT
42
3 5V | INT | DIGITAL
43
2 5V | INT | DIGITAL
Page 7
Basic Circuit
The basic circuit for the 28-pin Micromite is shown below. Because the Micromite only consists of the PIC32
chip and one capacitor it is recommended that you experiment with it using a plug in breadboard with jumper
leads. Later, when you have finalised your design you can create a printed circuit board to hold the final
circuit.
Power Supply
The Micromite needs a power supply between 2.3V and 3.6V connected as shown above. Normally the current
drain is 26mA plus the drain of any external components (LEDS, etc). Two alkaline AA cells can provide a
convenient power source or you can use a conventional power supply.
Generally it is a good design technique to place a 100nF ceramic capacitor close to each of the power supply
pins but this is not critical and they are not shown in this diagram.
The capacitor connected to pin 20 is used to decouple and stabilise the 1.8V voltage regulator internal to the
PIC32 chip. It must be a high quality capacitor (not an electrolytic) and should have a minimum value of 10F
with an ESR (Equivalent Series Resistance) of less than 1. The recommended capacitor is a 47F tantalum or
a 10F multilayer ceramic.
Terminal Emulator
To enter, edit and debug BASIC programs you need a terminal emulator connected to the Micromite via a serial
communications link. The emulator could be running on a Windows, Mac or Linux computer or it could be a
stand alone terminal.
The terminal emulator that you use should support VT100 emulation as that is what the editor built into the
Micromite expects. For Windows users it is recommended that you use Tera Term as this has a good VT100
emulator and is known to work with the XModem protocol which you can use to transfer programs to and from
the Micromite (Tera Term can be downloaded from: http://ttssh2.sourceforge.jp/).
Micromite MkII User Manual
Page 8
Serial Interface
The terminal emulator communicates with the Micromite via a serial communications link. This link must run
at 38400 baud and use TTL voltage levels (0 to 3.3V) not RS232 which runs at 12 volts. There are many
USB to TTL serial converters on the Internet and eBay for as cheap as $10. Use Google to search for "USB to
TTL serial". A typical device is this one: http://www.sparkfun.com/products/718
Connect the USB to TTL serial converter to the Micromite as shown in the diagram above. Transmit from the
converter should connect to pin 12 and receive should connect to pin 11.
If you have a serial converter that operates at 5V you can still use it with the Micromite. All you need do is
place a 1K resistor in series with the transmit signal from the converter. The protection diodes inside the PIC32
will clip the input signal to the supply voltage and the 1K resistor will limit the current to a safe level.
The serial converter will appear on your computer as a virtual serial port. You can then run a terminal emulator
on your computer and connect to this virtual serial port. When you do this you should set the baud rate to
38400 and the protocol to 8 bits no parity.
If you are using Tera Term do not set a delay between characters and if you are using Putty set the backspace
key to generate the backspace character.
The following screen shot shows the setup for Tera Term. Note that the "Port:" setting will vary depending on
which USB port your USB to TTL serial converter was plugged into.
When you have done this, apply power to the Micromite and you should see the MMBasic banner and prompt
on your screen similar to that shown below.
Page 9
A Simple Program
Assuming that you have correctly connected a terminal emulator to the Micromite and have the command
prompt (the greater than symbol as shown above, ie, > ) you can enter a command line followed by the enter
key and it will be immediately run.
For example, if you enter the command PRINT 1/7 you should see this:
> PRINT 1/7
0.142857
>
This is called immediate mode and is useful for testing commands and their effects.
To enter a program you can use the EDIT command which is fully described later in this manual. However to
get a quick feel for how it works, try this sequence (your terminal emulator must be VT100 compatible):
At the command prompt type EDIT followed by the ENTER key.
The editor should start up and you can enter this line: PRINT "Hello World"
Press the F1 key in your terminal emulator (or CTRL-Q which will do the same thing). This tells the
editor to save your program and exit to the command prompt.
Congratulations. You have just written and run your first program on the Micromite. If you type EDIT again
you will be back in the editor where you could change or add to your program.
Flashing a LED
Connect a LED to pin 15 as shown in the diagram on the right.
Then use the EDIT command to enter the following program:
SETPIN 15, DOUT
DO
PIN(15) = 1
PAUSE 300
PIN(15) = 0
PAUSE 300
LOOP
15
82
ohms
LED
When you have saved and run this program you should be greeted by the LED flashing on and off. It is not a
great program but it does illustrate how your Micromite can interface to the physical world via your
programming.
The section "Using the I/O pins" later in this manual provides a full description of the I/O pins and how to
control them.
Page 10
Using MMBasic
Commands and Program Input
At the command prompt you can enter a command and it will be immediately run. Most of the time you will
do this to tell the Micromite to do something like run a program or set an option. But this feature also allows
you to test out commands at the command prompt.
To enter a program the easiest method is to use the EDIT command. This will invoke the full screen program
editor which is built into the Micromite and is described later in this manual. It includes advanced features
such as search and copy, cut and paste to and from a clipboard.
You could also compose the program on your desktop computer using something like Notepad and then
transfer it to the Micromite via the XModem protocol (see the XMODEM command) or by streaming it up the
console serial link (see the AUTOSAVE command).
A third and very convenient method of writing and debugging a program is to use MMEdit. This is a program
running on your Windows or Linux computer which allows you to edit your program on your computer then
transfer it to the Micromite with a single click of the mouse. MMEdit was written by Jim Hiley and can be
downloaded for free from http://www.c-com.com.au/MMedit.htm.
With all of these methods of entering and editing a program the result is saved in non volatile flash memory
(this is transparent to the user). With the program held in flash memory it means that it will never be lost, even
when the power is unexpectedly interrupted or the processor restarted.
One thing that you cannot do is use the old BASIC way of entering a program which was to prefix each line
with a line number. Line numbers are optional in MMBasic so you can still use them if you wish but if you
enter a line with a line number at the prompt MMBasic will simply execute it immediately.
A label has the same specifications (length, character set, etc) as a variable name but it cannot be the
same as a command name. When used to label a line the label must appear at the beginning of a line
but after a line number (if used), and be terminated with a colon character (:).
Commands such as GOTO can use labels or line numbers to identify the destination (in that case the label does
not need to be followed by the colon character). For example:
GOTO xxxx
- - xxxx: PRINT "We have jumped to here"
Multiple commands separated by a colon can be entered on the one line (as in INPUT A : PRINT B).
Running Programs
A program is set running by the RUN command. You can interrupt MMBasic and the running program at any
time by typing CTRL-C on the console input and MMBasic will return to the command prompt.
You can list a program in memory with the LIST command. This will print out the program while pausing
every 24 lines.
You can completely erase the program by using the NEW command.
A program in the Micromite is held in non volatile flash memory. This means that it will not be lost if the
power is removed and, if you have the AUTORUN feature turned on, the Micromite will start by automatically
running the program when power is restored (use the OPTION command to turn AUTORUN on).
Setting Options
Many options can be set by using commands that start with the keyword OPTION. They are listed in the
commands section of this manual but, for example, you can set the baud rate of the console with the command:
OPTION BAUDRATE 9600
Page 11
Shortcut Keys
When you are using a VT100 compatible terminal emulator on the console you can use the function keys to
insert a command at the command prompt. These shortcut keys are:
F2
RUN
F3
LIST
F4
EDIT
F10
AUTOSAVE
F11
XMODEM RECEIVE
F12
XMODEM SEND
Pressing the key will insert the text at the command prompt, just as if it had been typed on the keyboard.
The Micromite's program is stored in the internal flash memory and is not lost when the power is cycled.
The ability to enter a program at the command prompt by preceding each line with a line number is not
available on the Micromite. Similarly the DELETE command is not available. To enter and modify
programs on the Micromite use the full screen editor.
The SETPIN command now accepts mnemonic identifiers for the mode of the pin and these are much
easier to remember. For example you can now specify SETPIN 14, DIN instead of SETPIN 14, 2. The
old numbers are still accepted.
A new interrupt type has been added - you can now interrupt on any input change (hi to low or low to hi).
Some of the maximum numbers have been reduced. For example the maximum number of nested
GOSUBs is now 30 (reduced from 100). This is to save on memory.
The AUTO command has been partially replaced with the AUTOSAVE command.
The LIST command has an option (LIST ALL) to list the program without stopping so that it can be
captured by the terminal emulator connected to the console (an alternative method of transferring a
program).
The OPTION and CONFIG commands have been merged to OPTION. New options have been added for
the console baud rate, the AUTORUN feature and setting a security PIN.
The FORMAT$() function, and the WRITE command are not implemented. The STR$() function has
been extended to replace some of the formatting functions previously provided by FORMAT$().
The CPU command has been added to change the processor speed or put it to sleep.
COM1: can now run at speeds up to 230400 and supports the enable signal and 9 bit data for IEEE 485.
The new invert option allows direct interfacing to RS232 circuits. On both COM1: and COM2: the send
buffer is fixed at 256 bytes (the receive buffer is still configurable).
The I2C commands have been renamed but have the same functionality. A string can now be used when
receiving data. Master interrupts, the NUM2BYTE command and BYTE2NUM () function are not
implemented (the PEEK function and POKE commands can be used to replace them).
The 1-Wire commands have been renamed but have the same functionality. You cannot use an array or
string variable for 'data' and the reset command does not accept a 'presence' variable (use the
MM.ONEWIRE variable instead). The OWCRC8() and OWCRC16() functions are not implemented.
The SPI command can now run with a clock speed up to 10MHz. The SPI function first needs to be
opened and then closed when the function is no longer required. There is one SPI channel and it is fixed
to a certain set of I/O pins.
There are five PWM channels in two groups and the frequency of each group can be set independently.
Page 12
Current Draw
48MHz
31mA
40MHz (default)
26mA
30MHz
21mA
20MHz
15mA
10MHz
10mA
5MHz
6mA
When the clock speed is changed all the serial ports (including the console) will be unaffected although there
may be a small glitch at the moment of change. The internal clocks and timers will also be unaffected. PWM,
SPI and I2C will have their speeds changed proportionally so if this is not required they should be closed before
the change and reopened after.
CPU Sleep
The CPU SLEEP command will put the processor to sleep for a certain number of seconds or monitor the
WAKEUP pin for a wakeup signal. During sleep the current drain is 90 to 100A.
Normal use for the command is CPU SLEEP seconds and in that case the CPU will sleep for the specified
number of seconds. The sleep time can be quite short (say 5 seconds) and, on waking up, the program can
make a quick check and if there is nothing to do go back to sleep again. Because the time awake would be so
short the average current drain would be small. Alternatively the sleep time can be quite large (up to 10 days).
If the timeout is not specified this command will automatically configure the WAKEUP pin as a digital input.
During sleep this pin will be monitored and the CPU woken up when its input changes state (ie, goes from high
to low or low to high). The wakeup signal could be a button press, an incoming signal or some other external
interrupt.
In this mode the sleep function will also work with the IR command (for receiving key presses from a remote
control) which shares the same I/O pin as the wakeup function. This means that an IR signal can be used to
Page 13
wakeup the Micromite which will then immediately decode the signal. The program can then do whatever it
needs to do in response to the remote control key press then go back to sleep and wait for the next command.
Watchdog Timer
The main use for the Micromite is as an embedded controller. It can be programmed in MMBasic and when
the program is debugged and ready for "prime time" the AUTORUN configuration setting can be turned on.
The chip will then automatically run its program when power is applied and act as a custom integrated circuit
performing some special task. The user need not know anything about what is running inside the chip.
However there is the possibility that a fault in the program could cause MMBasic to generate an error and
return to the command prompt. This would be of little use in an embedded situation as the Micromite would
not have anything connected to the console. Another possibility is that the BASIC program could get itself
stuck in an endless loop for some reason. In both cases the visible effect would be the same the program
would stop running until the power was cycled.
To guard against this the watchdog timer should be used. This is a timer that counts down to zero and when it
reaches zero the processor will be automatically restarted (the same as when power was first applied), even if
MMBasic was sitting at the command prompt. The automatic variable MM.WATCHDOG will also be set to
true to indicate that the restart was caused by a watchdog timeout.
The WATCHDOG command should 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 the AUTORUN option is set).
PIN Security
Sometimes it is important to keep the data and program in an embedded controller confidential. In the
Micromite this can be done by using the OPTION PIN command. This command will set a pin number (which
is stored in flash) and whenever the Micromite returns to the command prompt (for whatever reason) the user at
the console will be prompted to enter the PIN number. Without the correct PIN the user cannot get to the
command prompt and their only option is to enter the correct PIN or reboot the Micromite. When it is rebooted
the user will still need the correct PIN to access the command prompt.
Because an intruder cannot reach the command prompt they cannot list or copy a program, they cannot change
the program or change any aspect of MMBasic or the Micromite. Once set the PIN can only be removed by
providing the correct PIN as set in the first place. If the number is lost the only method of recovery is to reset
MMBasic as described below (which will erase the program).
There are other time consuming ways of accessing the data (such as using a PIC32 programmer to examine the
flash memory) so this should not be regarded as the ultimate security but it does act as a significant deterrent.
Resetting MMBasic
MMBasic can be reset to its original configuration using either one of two methods:
The chip can be reprogrammed with the Micromite firmware using a PIC32 programmer.
It can be reset by joining the console Tx and Rx pins together and then applying power. Following this,
wait a couple of seconds then remove the power followed by the link joining the two pins.
Page 14
Either method will result in the program memory and saved variables being completely erased and all options
(security PIN, console baud rate, etc) will be reset to their initial defaults.
64-bit Integers
MMBasic on the Micromite MkII supports 64-bit integers in addition to floating point. These can be used to
store and manipulate very large numbers up to 19 digits ( 9223372036854775807 to be precise) without loss
of accuracy (as against floating point which has a limit of about 7 significant digits). Integers are also slightly
faster (about 25%) than floating point.
Integers can be specified by adding the suffix "%" to a variable's name (eg, count%, j%, etc) and by using
constants without a decimal point. When working with integers it is best to keep all variables and numbers
involved in the calculations defined as integers however you can mix the two if needed (with possible loss of
precision). See the section "Defining and Using Variables" which provides more detail on this subject.
MMBasic with 64-bit integers is fully backwards compatible with programs written for earlier versions so they
can run unchanged. For normal use 64-bit integers can be ignored however some applications, especially
programs involved in communicating with other chips, will benefit from this level of precision while
manipulating large numbers.
The Micromite will start up in about 4mS but in some cases it might be necessary
to delay the start up to allow other circuitry (such as a USB-to-serial bridge) to start
up first.
This can be accomplished by delaying the rising edge of the voltage on pin 1 (on
the 28-pin chip) or 18 (on the 44-pin chip) which will have the effect of holding the
Micromite in reset. A suitable circuit is shown on the right. The delay is set by the
combination of the 50K resistor and the 47F capacitor and, with the values shown,
will delay start up by about 350mS.
The 1K resistor is there to ensure the safe discharge of the 47F capacitor when the
power is removed.
2.3 to 3.6V
50K
1K
+
47F
Micromite
Delayed Start Up
Page 15
Page 16
The IR function uses the same I/O pin as the wakeup signal for the CPU SLEEP command and it is possible to
combine them so that an incoming IR signal will wake the Micromite which will then decode the IR signal. In
this way you can have a Micromite running on battery power that will wake up on an IR signal, do something
based on the signal, then go back to sleep.
The following is an example:
IR DevCode, KeyCode, IR_Int
' start the IR decoder
DO
CPU SLEEP
' now sleep until a signal
LOOP
IR_Int:
' a key press has been detected
< do some work based on the key press >
IRETURN
' return to sleep again
Measuring Temperature
The DS18B20() function will get the temperature from a DS18B20 temperature sensor. This device can be
purchased on eBay for about $5 in a variety of packages including a waterproof probe version.
The DS18B20 can be powered separately by a 3V to 5V supply
or it can operate on parasitic power from the Micromite as
shown on the right. Multiple sensors can be used but a separate
3V to
I/O pin and pullup resistor is required for each one.
5V
To get the current temperature you just use the DS18B20()
4.7K
function in an expression.
Any
For example:
Micromite
PRINT "Temperature: " DS18B20(pin)
I/O Pin
Where 'pin' is the I/O pin to which the sensor is connected. You
do not have to configure the I/O pin, that is handled by
MMBasic.
The returned value is in degrees C with a resolution of 0.25C
and is accurate to 0.5 C. If there is an error during the measurement the returned value will be 1000.
The time required for the overall measurement is 200mS and the running program will halt for this period while
the measurement is being made. This also means that interrupts will be disabled for this period. If you do not
want this you can separately trigger the conversion using the DS18B20 START command then later use the
DS18B20() function to retrieve the temperature reading. The DS18B20() function will always wait if the
sensor is still making the measurement.
Page 17
For example:
DS18B20 START 15
< do other tasks >
PRINT "Temperature: " DS18B20(15)
I/O Pin
Where 'pin' is the I/O pin to which the sensor is connected. You can use any I/O pin but if the DHT22 is
powered from 5V it must be 5V capable. The I/O pin will be automatically configured by MMBasic.
'tVar' is a floating point variable in which the temperature is returned and 'hVar' is a second variable for the
humidity. The temperature is returned as degrees C with a resolution of one decimal place (eg, 23.4) and the
humidity is returned as a percentage relative humidity (eg, 54.3). If there is an error (eg, the sensor is not
connected or communicating correctly) the command will return 1000 for both the temperature and humidity.
For example:
DHT22 pin, temp, humid
PRINT "The temperature is" temp " and the humidity is" humid
The datasheet recommends a one second delay after power up before the first reading is made and a two second
interval between each measurement.
Controlling a Servo
Servos are a motor with integrated gears and a control system that allows the position of the shaft to be
precisely controlled. The Micromite can simultaneously control up to five servos.
Standard servos allow the shaft to be positioned at various angles, usually
between -90 and +90 degrees. Continuous rotation servos allow the rotation of
the shaft to be set to various speeds.
The position of the servo is controlled by a pulse which is repeated every
20mS. Generally a pulse width of 0.8mS will position the rotor at -90, a pulse
width of 2.2mS will position it at +90 and 1.5mS will centre the rotor. These
numbers can vary considerably between manufacturers.
Depending on their size servos can be quite powerful and provide a convenient
way for the Micromite to control the mechanical world.
Most servos require a high current 5V power source and have two power leads,
red for +V and black for ground. The third wire is the control signal which
should be connected to a Micromite SERVO I/O pin.
The Micromite has two servo controllers with the first being able to control up to three servos and the second
two servos. To drive the servo you use this command for the servos connected to controller 1:
SERVO 1, 1A, 1B, 1C
And this for servos connected to controller 2:
SERVO 2, 2A, 2B
Where 1A, 1B, 2A, etc are the desired pulse widths in milliseconds for each output of the channel. The output
pins are listed on pages 6 and 7 where the outputs are designated as PWM 1A, PWM 1B, PWM 2A, etc (the
Micromite MkII User Manual
Page 18
PWM and SERVO commands are closely related and use the same I/O pins). If you want to control less than
this number of servos you can leave the unused output off the list and use that pin as a general purpose I/O.
The pulse width can be specified with a high resolution (about 0.005 mS). For example, the following will
position the rotor of the servo connected to channel 1A to near its centre:
SERVO 1, 1.525
Following the SERVO command the Micromite will generate a continuous stream of pulses in the background
until another servo command is given or the STOP option is used (which will terminate the output).
As another example, the following will swing two servos back and forth alternatively every 5 seconds: These
servos should be connected to the outputs PWM 1A and PWM 1B.
DO
SERVO 1, 0.8, 2.2
PAUSE 5000
SERVO 1, 2.2, 0.8
PAUSE 5000
LOOP
3.3V
+
4.7K
Lithium 3V
button cell
battery
4.7K
8
28-pin
Micromite
18
17
3
2
5
6
DS1307
1
32.768
kHz
crystal
SetTime:
RTC GETTIME
IRETURN
Page 19
LCD Display
The LCD command will display text on a standard LCD module with the
minimum of programming effort.
This command will work with LCD modules that use the KS0066,
HD44780 or SPLC780 controller chip and have 1, 2 or 4 lines. Typical
displays include the LCD16X2 (futurlec.com), the Z7001
(altronics.com.au) and the QP5512 (jaycar.com.au). eBay is another
good source where prices can range from $10 to $50.
To setup the display you use the LCD INIT command:
LCD INIT d4, d5, d6, d7, rs, en
d4, d5, d6 and d7 are the numbers of the I/O pins that connect to inputs D4, D5, D6 and D7 on the LCD module
(inputs D0 to D3 and R/W on the module should be connected to ground). 'rs' is the pin connected to the
register select input on the module (sometimes called CMD or DAT). 'en' is the pin connected to the enable or
chip select input on the module.
Any I/O pins on the Micromite can be used and you do not have to set them up beforehand (the LCD command
automatically does that for you). The following shows a typical set up.
Note that this example also uses the DS18B20 function to get the temperature (described above).
Page 20
Keypad Interface
A keypad is a low tech method of entering data into a Micromite based system. The Micromite supports either
a 4x3 keypad or a 4x4 keypad and the monitoring and decoding of key presses is done in the background.
When a key press is detected an interrupt will be issued where the program can deal with it.
Examples of a 4x3 keypad and a 4x4 keypad are the Altronics S5381 and S5383 (go to www.altronics.com).
To enable the keypad feature you use the command:
KEYPAD
Where var is a variable that will be updated with the key code and int is the label of the interrupt to call when a
new key press has been detected. r1, r2, r3 and r4 are the pin numbers used for the four row connections to the
keypad (see the diagram below) and c1, c2, c3 and c4 are the column connections. c4 is only used with 4x4
keypads and should be omitted if you are using a 4x3 keypad.
Any I/O pins on the Micromite can be used and you do not have to set them up beforehand, the KEYPAD
command will automatically do that for you.
+3.3V
R1
R2
R3
R4
Micromite
20
21
22
10
11
23
C1
C2
C3
C4
The detection and decoding of key presses is done in the background and the program will continue after this
command without interruption. When a key press is detected the value of the variable var will be set to the
number representing the key (this is the number inside the circles in the diagram above). Then the interrupt
will be called.
For example:
Keypad KeyCode, KP_Int, 2, 3, 4, 5, 21, 22, 23
' 4x3 keyboard
DO
< body of the program >
LOOP
KP_Int:
PRINT "Key press = " KeyCode
IRETURN
Page 21
Rotary Encoders
A rotary encoder is a handy method of adjusting the value of parameters in a
microcontroller project. A typical encoder can be mounted on a panel with a knob
and looks like a potentiometer. As the knob is turned it generates a series of signals
known as a Gray Code. The program fragment below shows how to decode this
code to update a variable in the Micromite.
A standard encoder has two outputs (labelled RA and RB) and a common ground.
The outputs should be wired with pullup resistors as shown below:
DO
< main body of the program >
LOOP
RInt:
IF PIN(3) = 1 then
Value = Value + 1
ELSE
Value = Value - 1
ENDIF
IRETURN
This program assumes that the encoder is connected to I/O pins 2 and 3 on the Micromite however any pins can
be used by changing the pin numbers in the program. "Value" is the variable whose value will be updated as
the shaft of the encoder is rotated.
Note that this program is intended for simple user input where a skipped or duplicated step is not considered
important. It is not suitable for high speed or precision input.
Program courtesy TZAdvantage on the Back Shed Forum.
Page 22
Switch Inputs
Often there is a need to use a switch as an input to a Micromite based project. This is easy to implement as a
Micromite MkII input can be specified with an internal pullup resistor. This resistor is internal to the
Micromite and (when specified) will be connect between the input pin and the 3.3V supply (it is about 100K).
This means that the switch can be connected between the ground and the input pin. When the switch is open
the input will be high (pulled up by the internal resistor) and when closed the input will be zero.
To specify a pullup resistor you use SETPIN as follows:
3.3V
SETPIN pin, DIN, PULLUP
When you use a switch you will also have to consider the
issue of contact bounce. This is when the switch contacts
mechanically touch and then bounce apart momentarily due
Internal
to the momentum of the mechanical assembly. Because the
100KO
Micromite runs very fast a BASIC program could see this as
a secession of quick button presses rather than a single press.
You could check for this in your program, for example by
checking 100mS after the first contact closure to confirm
Switch
Micromite
that the contacts are indeed closed.
100nF
MkII
A simpler solution is to connect a 100nF capacitor across the
switch contacts as illustrated on the right. This capacitor in
association with the internal pullup resistor will average out
any rapid contact bounce so that the program will see a
smooth transition from on to off and vice versa.
Measuring Distance
Using a HC-SR04 ultrasonic sensor and the DISTANCE() function you can measure the distance to a target.
This device can be found on eBay for about $4 and it will measure the
distance to a target from 3cm to 3m. It works by sending an ultrasonic
sound pulse and measuring the time it takes for the echo to be returned.
On the Micromite you use the DISTANCE function:
d = DISTANCE(trig, echo)
Where trig is the I/O pin connected to the "trig" input of the sensor and
echo is the pin connected "echo" output of the sensor. You can also use
3-pin devices and in that case only one pin number is specified.
The value returned is the distance in centimetres to the target or -1 if no
target was detected. If you repeatedly call this function you must arrange for a delay of at least 60mS between
each call otherwise errors may occur (caused by an echo from the previous sound pulse).
The I/O pins are automatically configured by this function but note that they should be 5V capable as the
HC-SR04 is a 5V device. You can use multiple sensors connected to different I/O pins or even sharing the one
trigger pin if care is taken to prevent one sensor from interfering with another.
Page 23
The full screen program editor is invoked with the EDIT command. The cursor will be automatically
positioned at the last place that you were editing at or, if your program had just been stopped by an error, the
cursor will be positioned at the line that caused the error.
If you are used to an editor like Notepad you will find that the operation of this editor is familiar. The arrow
keys will move your cursor around in the text, home and end will take you to the beginning or end of the line.
Page up and page down will do what their titles suggest. The delete key will delete the character at the cursor
and backspace will delete the character before the cursor. The insert key will toggle between insert and
overtype modes.
About the only unusual key combination is that two home key presses will take you to the start of the program
and two end key presses will take you to the end.
At the bottom of the screen the status line will list the various function keys used by the editor and their action.
In more details these are:
ESC
This will cause the editor to abandon all changes and return to the command prompt with
the program memory unchanged. If you have changed the text you will be asked if you
really what want to abandon your changes.
F1: SAVE
This will save the program to program memory and return to the command prompt.
F2: RUN
This will save the program to program memory and immediately run it.
F3: FIND
This will prompt for the text that you want to search for. When you press enter the
cursor will be placed at the start of the first entry found.
SHIFT-F3
Once you have used the search function you can repeatedly search for the same text by
pressing SHIFT-F3.
F4: MARK
F5: PASTE
This will insert (at the current cursor position) the text that had been previously cut or
copied (see below).
Page 24
If you pressed the mark key (F4) the editor will change to the mark mode. In this mode you can use the arrow
keys to mark a section of text which will be highlighted in reverse video. You can then delete, cut or copy the
marked text. In this mode the status line will change to show the functions of the function keys in the mark
mode. These keys are:
ESC
F4: CUT
Will copy the marked text to the clipboard and remove it from the program.
F5: COPY
DELETE
You can also use control keys instead of the functions keys listed above. These control keystrokes are:
LEFT
HOME
DEL
F3
Ctrl-S
Ctrl-U
Ctrl-]
Ctrl-R
RIGHT
END
INSERT
ShiftF3
Ctrl-D
Ctrl-K
Ctrl-N
Ctrl-G
UP
PageUp
F1
F4
Ctrl-E
Ctrl-P
Ctrl-Q
Ctrl-T
DOWN
PageDn
F2
F5
Ctrl-X
Ctrl-L
Ctrl-W
Ctrl-Y
The best way to learn the full screen editor is to simply fire it up and experiment.
The editor is a very productive method of writing a program. With the command EDIT you can write your
program on the Micromite. Then, by pressing the F2 key, you can save and run the program. If your program
stops with an error you can press the function key F4 which will run the command EDIT and place you back in
the editor with the cursor positioned at the line that caused the error. This edit/run/edit cycle is very fast.
Using the OPTION BAUDRATE command the baud rate of the console can be changed to any speed up to
230400 bps. Changing the console baud rate to a higher speed makes the full screen editor much faster in
redrawing the screen. If you have a reliable connection to the Micromite it is worth changing the speed to at
least 115200.
The editor expects that the terminal emulator is set to 24 lines per screen with each line 80 characters wide.
Both of these assumptions can be changed with the OPTION DISPLAY command to suit non standard
displays.
Note that a terminal emulator can lose its position in the text with multiple fast keystrokes (like the up and
down arrows). If this happens you can press the HOME key twice which will force the editor to jump to the
start of the program and redraw the display.
Page 25
OPTION DEFAULT
A variable can be used without a suffix (ie, !, % or $) and in that case MMBasic will use the default type of
floating point. For example, the following will create a floating point variable:
Nbr = 1234
However the default can be changed with the OPTION DEFAULT command. For example, OPTION
DEFAULT INTEGER will specify that all variables without a specific type will be integer. So, the following
will create an integer variable:
OPTION DEFAULT INTEGER
Nbr = 1234
The default can be set to FLOAT (which is the default when a program is run), INTEGER, STRING or NONE.
In the latter case all variables must be specifically typed otherwise an error will occur.
The OPTION DEFAULT command can be placed anywhere in the program and changed at any time but good
practice dictates that if it is used it should be placed at the start of the program and left unchanged.
OPTION EXPLICIT
By default MMBasic will automatically create a variable when it is first referenced. So, Nbr = 1234 will
create the variable and set it to the number 1234 at the same time. This is convenient for short and quick
programs but it can lead to subtle and difficult to find bugs in large programs. For example, in the third line of
this fragment the variable Nbr has been misspelt as Nr. As a consequence the variable Nr would be created
with a value of zero and the value of Total would be wrong.
Nbr = 1234
Incr = 2
Total = Nr + Incr
Micromite MkII User Manual
Page 26
The OPTION EXPLICIT command tells MMBasic to disallow the automatic creation of variables. Instead
they must be explicitly defined beforehand using the DIM or LOCAL commands (see below). If the OPTION
EXPLICIT command was used as shown below the error would become obvious when the program was run:
> LIST
OPTION EXPLICIT
DIM Nbr, Incr, Total
Nbr = 1234
Incr = 2
Total = Nr + Incr
>
> RUN
[5] Total = Nr + Incr
Error: Variable not declared
>
The use of OPTION EXPLICIT is recommended to support good programming practice. If it is used it should
be placed at the start of the program before any variables are used.
Page 27
CONST
Often it is useful to define an identifier that represents a value without risking the danger of the value being
accidently changed - which can happen if variables were used for this purpose (this practice encourages another
class of difficult to find bugs).
Using the CONST command you can create an identifier that acts like a variable but is set to a value that cannot
be changed. For example:
CONST InputVoltagePin = 26
CONST MaxValue = 2.4
The identifiers can then be used in a program where they make more sense to the casual reader than simple
numbers. For example:
IF PIN(InputVoltagePin) > MaxValue THEN SoundAlarm
A number of constants can be created on the one line:
CONST InputVoltagePin = 26, MaxValue = 2.4, MinValue = 1.5
The value used to initialise the constant is evaluated when the constant is created and can be an expression
including user defined functions.
The type of the constant is derived from the value assigned to it; so for example, MaxValue above will be a
floating point constant because 2.4 is a floating point value. The type of a constant can also be explicitly set by
using a type suffix (ie, !, % or $).
Page 28
Analog Inputs
Pins marked as ANALOG can be configured to measure the voltage on the pin. The input range is from zero to
3.3V and the PIN() function will return the voltage. For example:
> SETPIN 23, AIN
> PRINT PIN(23)
2.345
>
You will need a voltage divider if you want to measure voltages greater than 3.3V. For small voltages you may
need an amplifier to bring the input voltage into a reasonable range for measurement.
The measurement uses the analog power pin (pin 28 on the 28-pin chip and 17 on the 44-pin chip) as the
reference voltage and MMBasic scales the reading by assuming that the voltage on this pin is exactly 3.3V.
Normally the Micromite is powered from a voltage regulator so this assumption is correct. However, when
battery power is used, the supply voltage can vary which will cause inaccurate readings. In that case the
program should scale the reading accordingly. For example:
A = (PIN(x) / 3.3) * PowerV
where "PowerV" is the voltage on the analog power pin.
The Micromite contains an internal voltage reference of 1.2V (5%) which will remain constant regardless of
the power supply voltage. MMBasic allows you to measure this reference by using pin zero. ie, A =
PIN(0). Using this facility the voltage on the analog power pin can be inferred (ie, as the power varies from
3.3V the measurement of the reference voltage will vary accordingly). The following demonstrates how this
can be done.
PowerV = 3.3 / (PIN(0) / 1.2)
It is then possible to combine and simplify the two formulae to get a reasonably accurate reading when running
on a battery supply.
A = PIN(x) / (PIN(0) / 1.2)
The measurement of voltage is very sensitive to noise on the Analog Power and Ground pins. For accurate and
repeatable voltage measurements care should be taken with the PCB design to isolate the analog circuit from
the digital circuits and ensure that the Analog Power supply is as noise free as possible.
Page 29
Counting Inputs
The pins marked as COUNT can be configured as counting inputs to measure frequency, period or just count
pulses on the input.
For example, the following will print the frequency of the signal on pin 15:
> SETPIN 15, FIN
> PRINT PIN(15)
110374
>
In this case the frequency is 110.374 KHz.
By default the gate time is one second which is the length of time that MMBasic will use to count the number
of cycles on the input and this means that the reading is updated once a second with a resolution of 1 Hz. By
specifying a third argument to the SETPIN command it is possible to specify an alternative gate time between
10mS and 100000mS. Shorter times will result in the readings being updated more frequently but the value
returned will have a lower resolution. The PIN() function will always return the frequency in Hz regardless of
the gate time used.
For example, the following will set the gate time to 10mS with a corresponding loss of resolution:
> SETPIN 15, FIN, 10
> PRINT PIN(15)
110300
>
For accurate measurement of signals less than 10Hz it is generally better to measure the period of the signal.
When set to this mode the Micromite will measure the number of milliseconds between sequential rising edges
of the input signal. The value is updated on the low to high transition so if your signal has a period of (say) 100
seconds you should be prepared to wait that amount of time before the PIN() function will return an updated
value.
The COUNTING pins can also count the number of pulses on their input. When a pin is configured as a
counter (for example, SETPIN 15,CIN) the counter will be reset to zero and Micromite will then count every
transition from a low to high voltage. The counter can be reset to zero again by executing the SETPIN
command a second time (even though the input was already configured as a counter).
The response to input pulses is very fast and the Micromite can count pulses as narrow as 10nS . The
frequency response depends on the load on the processor (ie, the number of counting inputs and if serial or I2C
communications is used). It can be as high as 800KHz with no other activity but is normally about 300KHz.
Digital Outputs
All I/O pins can be configured as a standard digital output. This means that when an output pin is set to logic
low it will pull its output to zero and when set high it will pull its output to 3.3V. In MMBasic this is done
with the PIN command. For example PIN(15) = 0 will set pin 15 to low while PIN(15) = 1 will set it
high. When operating in this mode, a pin is capable of sourcing 10mA which is sufficient to drive a LED or
other logic circuits running at 3.3V.
The "OC" option on the SETPIN command makes the output pin open collector. This means that the output
driver will pull the output low (to zero volts) when the output is set to a logic low but will go to a high
impedance state when set to logic high. If you then connect a pull-up resistor to 5V (on pins that are 5V
tolerant) the logic high level will be 5V (instead of 3.3V using the standard output mode). The maximum pullup voltage in this mode is 5.5V.
Page 30
When the Micromite is powered up or the PWM OFF command is used the PWM outputs will be set to high
impedance (they are neither off nor on). So, if you want the PWM output to be low by default (zero power in
most applications) you should use a resistor to pull the output to ground when it is set to high impedance.
Similarly, if you want the default to be high (full power) you should connect the resistor to 3.3V.
Interrupts
Interrupts are a handy way of dealing with an event that can occur at an unpredictable time. An example is
when the user presses a button. In your program you could insert code after each statement to check to see if
the button has been pressed but an interrupt makes for a cleaner and more readable program.
When an interrupt occurs MMBasic will execute a special section of code and when finished return to the main
program. The main program is completely unaware of the interrupt and will carry on as normal.
I/O pins marked as INT can be configured to generate an interrupt using the SETPIN command with many
interrupts (including the tick interrupt) active at any one time. Interrupts can be set up to occur on a rising or
falling digital input signal (or both) and will cause an immediate branch to a specified line number, label or a
user defined subroutine. The target can be the same or different for each interrupt. Return from an interrupt is
via the IRETURN statement except where a user defined subroutine is used (in that case END SUB or EXIT
SUB is used). Within the interrupt routine GOTO, GOSUB and calls to other subroutines can be used.
If two or more interrupts occur at the same time they will be processed in order of pin numbers (ie, an interrupt
on pin 2 will have the highest priority). During the processing of an interrupt all other interrupts are disabled
until the interrupt routine returns. During an interrupt (and at all times) the value of the interrupt pin can be
accessed using the PIN() function.
Interrupts can occur at any time but they are disabled during INPUT statements. Also interrupts are not
recognised during some long hardware related operations (eg, the DS18B20() function) although they will be
recognised if they are still present when the operation has finished.. When using interrupts the main program is
completely unaffected by the interrupt activity unless a variable used by the main program is changed during
the interrupt.
For most programs MMBasic will respond to an interrupt in under 30S. To prevent slowing the main program
by too much an interrupt should be short and exit as soon as possible. Also remember to disable an interrupt
when you have finished needing it background interrupts can cause strange and non-intuitive bugs.
Page 31
Timing
MMBasic has a number of features that make it easy to time events and control external circuitry that needs
timing.
MMBasic maintains an internal clock. You can get the current date and time using the DATE$ and TIME$
functions and you can set them by assigning the new date and time to them. The calendar will start from zero
when the Micromite is first powered up but by using the I2C feature you can easily get the time from a real time
clock chip like the PCF8563.
The PAUSE command will freeze the execution of the program for a specified number of milliseconds. So, to
create a 12mS wide pulse you could use the following:
SETPIN 4, DOUT
PIN(4) = 1
PAUSE 12
PIN(4) = 0
You can also create a pulse using the PULSE command. This will generate very narrow pulses (eg, 20S) or
long pulses up to several days. Long pulses are run in the background and the program will continue
uninterrupted.
Another useful feature is the TIMER function which acts like a stopwatch. You can set it to any value (usually
zero) and it will count upwards every millisecond.
A timing function is also provided by the SETTICK command. This command will generate an interrupt at
regular intervals (specified in milliseconds). Think of it as the regular "tick" of a watch. For example, the
following code fragment will print the current time and the voltage on pin 2 every second. This process will
run independently of the main program which could be doing something completely unrelated.
SETPIN 2, AIN
SETTICK 1000, DOINT
DO
main processing loop
LOOP
DOINT:
tick interrupt
PRINT TIME$, PIN(2)
IRETURN
The second line sets up the "tick" interrupt, the first parameter of SETTICK is the period of the interrupt (1000
mS) and the second is the starting label of the interrupt code. Every second (ie, 1000 mS) the main processing
loop will be interrupted and the program starting at the label DOINT will be executed.
Up to four "tick" interrupts can be setup. These interrupts have the lowest priority.
The accuracy of the Micromite's internal clock can vary by a little due to manufacturing tolerances and
temperature. To compensate for this the OPTION CLOCKTRIM command can be used to trim the clock to a
more accurate value.
Page 32
Subroutine Arguments
Defined subroutines can have arguments (sometimes called parameter lists). In the definition of the subroutine
they look like this:
SUB MYSUB (arg1, arg2$, arg3)
<statements>
<statements>
END SUB
And when you call the subroutine you can assign values to the arguments. For example:
MYSUB 23, "Cat", 55
Inside the subroutine arg1 will have the value 23, arg2$ the value of "Cat", and so on. The arguments act
like ordinary variables but they exist only within the subroutine and will vanish when the subroutine ends. You
can have variables with the same name in the main program and they will be different from arguments defined
for the subroutine (at the risk of making debugging harder).
When calling a subroutine you can supply less than the required number of values. For example:
MYSUB 23
In that case the missing values will be assumed to be either zero or an empty string. For example, in the above
case arg2$ will be set to "" and arg3 will be set to zero. This allows you to have optional values and, if the
value is not supplied by the caller, you can take some special action.
You can also leave out a value in the middle of the list and the same will happen. For example:
MYSUB 23, , 55
Will result in arg2$ being set to "".
Rather than using the type suffix (eg, the $ in arg2$) you can use the suffix AS <type> in the definition of the
subroutine argument and then the argument will be known as the specified type, even when the suffix is not
used. For example:
SUB MYSUB (arg1, arg2 AS STRING, arg3)
IF arg2 = "Cat" THEN
END SUB
Local Variables
Inside a subroutine you will need to use variables for various tasks. In portable code you do not want the name
you chose for such a variable to clash with a variable of the same name in the main program. To this end you
can define a variable using LOCAL within the subroutine.
Micromite MkII User Manual
Page 33
For example, this is our FLASH subroutine but this time we have extended it to take an argument (nbr) that
specifies how many times to flash the LED.
SUB FLASH ( nbr )
LOCAL INTEGER count
SETPIN 2, DOUT
FOR count = 1 TO nbr
PIN(2) = 1
PAUSE 100
PIN(2) = 0
PAUSE 150
NEXT count
END SUB
The counting variable (count) is declared within the subroutine which means that (like the argument list) it
only exists within the subroutine and will vanish when the subroutine exits. You can have a variable called
count in your main program and it will be different from the variable count in your subroutine.
If you do not declare the variable within the subroutine and OPTION EXPLICIT is not in force it will be
created within your program and be visible in your main program and subroutines, just like a normal variable.
You can also use local variables in the target for GOSUBs. For example:
GOSUB MySub
...
MySub:
LOCAL X, Y
FOR X = 1 TO ...
FOR Y = 5 TO ...
<statements>
RETURN
The variables X and Y will only be valid until the RETURN statement is reached and will be different from
variables with the same name in the main body of the program.
Defined Functions
Defined functions are similar to defined subroutines with the main difference being that the function is used to
return a value in an expression. For example, if you wanted a function to select the maximum of two values
you could define:
FUNCTION Max(a, b)
IF a > b
Max = a
ELSE
Max = b
ENDIF
END FUNCTION
Then you could use it in an expression:
SETPIN 1, AIN : SETPIN 2, AIN
PRINT "The highest voltage is" Max(PIN(1), PIN(2))
The rules for the argument list in a function are similar to subroutines. The only difference is that brackets are
required around the argument list when you are calling a function (they are optional when calling a subroutine).
To return a value from the function you assign a value to the function's name within the function. If the
function's name is terminated with a $, a % or a ! the function will return that type, otherwise it will return
whatever the OPTION DEFAULT is set to.
You can also specify the type of the function by adding AS <type> to the end of the function definition. For
example:
FUNCTION Max(a, b) AS INTEGER
This is the same as saying:
FUNCTION Max%(a, b)
Within the function the function's name acts like a standard variable (an integer in this case).
Page 34
As another example, let us say that you need a function to format time in the AM/PM format:
FUNCTION MyTime$(hours, minutes)
LOCAL h
h = hours
IF hours > 12 THEN h = h - 12
MyTime$ = STR$(h) + ":" + STR$(minutes)
IF hours <= 12 THEN
MyTime$ = MyTime$ + "AM"
ELSE
MyTime$ = MyTime$ + "PM"
ENDIF
END FUNCTION
As you can see, the function name is used as an ordinary local variable inside the subroutine. It is only when
the function returns that the value assigned to MyTime$ is made available to the expression that called it.
This example also illustrates that you can use local variables within functions just like subroutines.
Passing Arrays
Single elements of an array can be passed to a subroutine or function and they will be treated the same
as a normal variable. For example, this is a valid way of calling the Swap subroutine (discussed above):
Swap dat(i), dat(i + 1)
This type of construct is often used in sorting arrays.
You can also pass one or more complete array to a subroutine or function by specifying the array with
empty brackets instead of the normal dimensions. For example, a(). In the subroutine or function
definition the associated parameter must also be specified with empty brackets. The type (ie, float,
integer or string) of the argument supplied and the parameter in the definition must be the same.
In the subroutine or function the array will inherit the dimensions of the array passed and these must
be respected when indexing into the array. If required the dimensions of the array could be passed as
additional arguments to the subroutine or function so it could correctly manipulate the array.
The array is passed by reference which means that any changes made to the array within the
subroutine or function will also apply to the supplied array.
Page 35
For example, when the following program is run the words "Hello World" will be printed out:
DIM str$(5, 5)
Str$(4, 4) = "Hello"
Str$(4, 5) = "World"
Concat$ str$()
PRINT Str$(0, 0)
SUB concat$ arg$()
arg$(0,0) = arg$(4, 4) + " " + arg$(4, 5)
END SUB
Additional Notes
There can be only one END SUB or END FUNCTION for each definition of a subroutine or function. To exit
early from a subroutine (ie, before the END SUB command has been reached) you can use the EXIT SUB
command. This has the same effect as if the program reached the END SUB statement. Similarly you can use
EXIT FUNCTION to exit early from a function.
Page 36
Electrical Characteristics
Power Supply
Voltage range:
Current at 48MHz:
Current at 5MHz:
Current in sleep:
Digital Inputs
Logic Low:
Logic High:
Input Impedance:
Frequency Response:
0 to 0.65V
2.5V to 3.3V on normal pins
2.5V to 5.5V on pins rated at 5V
>1M. All digital inputs are Schmitt Trigger buffered.
Up to 300KHz (pulse width 20nS or more) on the counting inputs (pins 15 to 18).
Analog Inputs
Voltage Range:
Accuracy:
Input Impedance:
0 to 3.3V
Analog measurements are referenced to the supply voltage on pin 28 and the
ground on pin 27. If the supply voltage is precisely 3.3V the typical accuracy of
readings will be 1%.
>1M (for accurate readings the source impedance should be <10K)
Digital Outputs
Typical current draw or sink ability on any I/O pin:
Absolute maximum current draw or sink on any I/O pin:
Absolute maximum current draw or sink for all I/O pins combined:
Maximum open collector voltage:
10mA
15mA
200mA
5.5V
Timing Accuracy
All timing functions (the timer, tick interrupts, PWM frequency, baud rate, etc) are dependent on the
internal fast RC oscillator which has a specified tolerance of 0.9% but typically is within 0.1% at 24C.
PWM Output
Frequency range:
Duty cycle:
20Hz to 500KHz
0% to 100% with 0.1% resolution below 25KHz
10Hz to 10MHz (at 40MHz). Limited to one quarter of the clock speed.
10KHz to 400KHz.
Fixed at 15KHz.
Flash Endurance
Over 20,000 erase/write cycles.
Every program save incurs one erase/write cycle. In a normal program development it is highly unlikely
that more than a few hundred program saves would be required.
Saved variables (VAR SAVE command) and configuration options (the OPTION command) are saved in a
different flash area and use one erase/write cycle each time the command is used. Usage of the VAR
SAVE command should be limited to an average of once a day over the entire life of the chip (50 years).
Micromite MkII User Manual
Page 37
MMBasic Characteristics
Naming Conventions
Command names, function names, labels, variable names, file names, etc are not case sensitive, so that "Run"
and "RUN" are equivalent and "dOO" and "Doo" refer to the same variable.
There are three types of variables:
4. Floating point. These can store a number with a decimal point and fraction (eg, 45.386) and also very
large numbers. However, they will loose accuracy when more than seven significant digits are stored or
manipulated. These are specified by adding the suffix '!' to a variable's name and are the default when a
variable is created without a suffix (eg, i, nbr, etc).
5. 64-bit integer. These can store numbers with up to 19 decimal digits without loosing accuracy but they
cannot store fractions (ie, the part following the decimal point). These are specified by adding the suffix
'%' to a variable's name. For example, i%, nbr%, etc.
6. Strings. These will store a string of characters (eg, "Tom"). String variable names are terminated with a
'$' symbol (eg, name$, s$, etc). Strings can be up to 255 characters long.
Variable names and labels can start with an alphabetic character or underscore and can contain any alphabetic
or numeric character, the period (.) and the underscore (_). They may be up to 32 characters long. A variable
name or a label must not be the same as a command or a function or one of the following keywords: THEN,
ELSE, TO, STEP, FOR, WHILE, UNTIL, MOD, NOT, AND, OR, XOR, AS. Eg, step = 5 is illegal.
Constants
Numeric constants may begin with a numeric digit (0-9) for a decimal constant, &H for a hexadecimal
constant, &O for an octal constant or &B for a binary constant. For example &B1000 is the same as the
decimal constant 8. Constants that start with &H, &O or &B are always treated as 64-bit integer constants.
Decimal constants may be preceded with a minus (-) or plus (+) and may be terminated with 'E' followed by an
exponent number to denote exponential notation. For example 1.6E+4 is the same as 16000.
If the decimal constant contains a decimal point or an exponent, it will be treated as a floating point constant;
otherwise it will be treated as a 64-bit integer constant.
String constants are surrounded by double quote marks ("). Eg, "Hello World".
Exponentiation
* / \ MOD
+ -
Shift operators:
x << y
x >> y
These operate in a special way. << means that the value returned
will be the value of x shifted by y bits to the left while >> means the
same only right shifted. They are integer functions and any bits
shifted off are discarded and any bits introduced are set to zero.
Logical operators:
NOT
<>
>=
=
AND
Inequality, less than, greater than, less than or equal to, less than or
equal to (alternative version), greater than or equal to, greater than or
equal to (alternative version)
equality
OR
XOR
Page 38
The operators AND, OR and XOR are integer bitwise operators. For example PRINT 3 AND 6 will output 2.
The other logical operations result in the integer 0 (zero) for false and 1 for true. For example the statement
PRINT 4 >= 5 will print the number zero on the output and the expression A = 3 > 2 will store +1 in A.
The NOT operator is highest in precedence so it will bind tightly to the next value. For normal use the
expression to be negated should be placed in brackets. For example, IF NOT (A = 3 OR A = 8) THEN
String operators:
+
<>
>=
Inequality, less than, greater than, less than or equal to, less than or
equal to (alternative version), greater than or equal to, greater than or
equal to (alternative version)
Equality
Implementation Characteristics
Maximum program size (as plain text) is 53K. Note that MMBasic tokenises the program when it is stored in
flash so the final size in flash might vary from the plain text size.
Maximum length of a command line is 255 characters.
Maximum length of a variable name or a label is 32 characters.
Maximum number of dimensions to an array is 8.
Maximum number of arguments to commands that accept a variable number of arguments is 50.
Maximum number of nested FORNEXT loops is 10.
Maximum number of nested DOLOOP commands is 10.
Maximum number of nested GOSUBs, subroutines and functions (combined) is 50.
Maximum number of nested multiline IFELSEENDIF commands is 10.
Maximum number of user defined subroutines and functions (combined): 100
Numbers are stored and manipulated as single precision floating point numbers or 64-bit signed integers. The
maximum floating point number allowable is 3.40282347e+38 and the minimum is 1.17549435e-38.
The range of 64-bit integers (whole numbers) that can be manipulated is 9223372036854775807.
Maximum string length is 255 characters.
Maximum line number is 65000.
Maximum number of background pulses launched by the PULSE command is 5.
Compatibility
MMBasic implements a large subset of Microsofts GW-BASIC. There are numerous small differences due to
physical and practical considerations but most MMBasic commands and functions are essentially the same. An
online manual for GW-BASIC is available at http://www.antonis.de/qbebooks/gwbasman/index.html and this
provides a more detailed description of the commands and functions.
MMBasic also implements a number of modern programming structures documented in the ANSI Standard for
Full BASIC (X3.113-1987) or ISO/IEC 10279:1991. These include SUB/END SUB, the DO WHILE
LOOP, the SELECTCASE statements and structured IF .. THEN ELSE ENDIF statements.
License
MMBasic is Copyright 2011-2015 by Geoff Graham - http://mmbasic.com.
The compiled object code (the .hex file) is free software: you can use or redistribute it as you please.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
The source code is available via subscription (free of charge) to individuals for personal use or under a
negotiated license for commercial use. In both cases go to http://mmbasic.com for details.
This manual is distributed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Australia
license (CC BY-NC-SA 3.0)
Page 39
The version number of the firmware in the form aa.bbcc where aa is the
major version number, bb is the minor version number and cc is the revision
number (normally zero but A = 01, B = 02, etc).
MM.DEVICE$
MM.WATCHDOG
True if MMBasic was restarted as the result of a Watchdog timeout (see the
WATCHDOG command). False if MMBasic started up normally.
MM.I2C
Following an I2C write or read command this variable will be set to indicate
the result of the operation as follows:
0 = The command completed without error.
1 = Received a NACK response
2 = Command timed out
MM.ONEWIRE
Following a 1-Wire reset function this variable will be set to indicate the
result of the operation as follows:
0 = Device not found.
1 = Device found
Page 40
Commands
Detailed Listing
Note that the commands related to the I2C, 1-Wire, and SPI communications functions are not listed here but
are described in the appendices at the end of this document.
Square brackets indicate that the parameter or characters are optional.
(single quotation mark)
Starts a comment and any text following it will be ignored. Comments can
be placed anywhere on a line.
? (question mark)
AUTOSAVE
CFUNCTION name
hex [[ hex[]
hex [[ hex[]
END CFUNCTION
Defines the binary code for a program module (a "C Function") written in C
or MIPS assembler. The module will appear in MMBasic as the function
'name' and can be used in the same manner as a built-in function.
This command specifies the hex codes for the module. These are
automatically programmed into MMBasic when the program is saved. Each
'hex' must be exactly eight hex digits representing the bits in a 32-bit word.
Each 'hex' word must be separated by one or more spaces and multiple
lines of 'hex' words can be used. The command must be terminated by
a matching END CFUNCTION.
The first 'hex' word must be the offset (in 32-bit words) to the entry
point of the CFunction (usually the function main()).
Multiple CFUNCTION commands can be used with each defining a
different module with a different 'name'.
During execution MMBasic will skip over any CFUNCTION
commands so they can be placed anywhere in the program.
Any errors in the data format will be reported when the program is saved.
The function 'name' created by the CFUNCTION command can be used as a
normal function within MMBasic with a few caveats:
The function will always return an integer.
Up to ten values can be specified as parameters ('arg1', 'arg2', etc) and
they will be passed to the C function as pointers to the memory space
allocated to each value (ie, the result of the expression).
If a variable or array is specified as an argument the C function will
receive a pointer to the memory allocated to the variable or array and
the C function can change this memory to return a value to the caller.
In the case of arrays, they should be passed with empty brackets. eg,
arg(). In the C function the argument will be supplied as a pointer to
the first element of the array.
For more details and a tutorial on using this feature refer to:
http://geoffg.net/Downloads/Micromite/cfunctions.pdf
WARNING: No validation is made and faulty code in the module can cause
a CPU exception which will force the Micromite to restart without warning.
Page 41
CLEAR
Close the serial communications port(s) previously opened with the file
number nbr. The # is optional. Also see the OPEN command.
CONST id = expression
[, id = expression] etc
CONTINUE
CPU speed
Put the CPU to sleep. In this mode the running program will be halted and
the current drain reduced considerably.
In the first form (CPU SLEEP seconds) the command will put the CPU to
sleep for the specified number of 'seconds' (maximum of 10 days). The
current drain in this mode is about 90A. This command will update the
TIMER function when it comes out of sleep but note that the sleep time is
not very accurate, it can vary by up to 20%.
In the second form the WAKEUP pin (pin16 on 28-pin devices and pin 43
on 44-pin devices) will be automatically configured as a digital input and
any change in its state (ie, from high to low or low to high) will wakeup the
CPU. The current drain in this mode is about 80A.
The IR command shares the WAKEUP pin and if it is running the CPU will
be awakened by the remote key press and MMBasic will immediately
decode the signal and execute the IR interrupt.
Notes:
The CPU will go to sleep in the middle of the SLEEP command and
when awakened continue with normal program execution.
All communications (serial, SPI, I2C and 1-Wire) and PWM will be
frozen during sleep. When the CPU comes out of sleep they will resume
normal processing. It is recommended that they be closed before
entering sleep as they will add to the current drawn by the chip in sleep.
The time required to "wake up" ranges from 0.4mS at a CPU speed of
Page 42
DATA constant[,constant]...
DATE$ = "DD-MM-YY"
or
DATE$ = "DD/MM/YY"
Returns the temperature and humidity using the DHT22 sensor. Alternative
versions of the DHT22 are the AM2303 or the RHT03 (all are compatible).
'pin' is the I/O pin connected to the sensor. Any I/O pin may be used.
'tvar' is the variable that will hold the measured temperature and 'hvar' is the
same for humidity. Both must be present and both must be floating point
variables.
For example: DHT22 2, TEMP!, HUMIDITY!
Temperature is measured in C and the humidity is percent relative humidity.
Both will be measured with a resolution of 0.1. If an error occurs (sensor not
connected or corrupt signal) both values will be 1000.0. The CPU speed
must be 10MHz or higher and the measurement will take 6mS to complete.
Normally the signal pin of the DHT22 should be pulled up by a 1K to 10K
resistor (4.7K recommended) to the supply voltage. The Micromite will also
enable an internal high value pullup resistor so when the cable length is short
(under 30cm) the external pullup resistor may be omitted.
Declares one or more variables (ie, makes the variable name and its
characteristics known to the interpreter).
When OPTION EXPLICIT is used (as recommended) the DIM or LOCAL
commands are the only way that a variable can be created. If this option is
not used then using the DIM command is optional and if not used the
variable will be created automatically when first referenced.
The type of the variable (ie, string, float or integer) can be specified in one of
three ways:
By using a type suffix (ie, !, % or $ for float, integer or string). For
example:
DIM nbr%, amount!, name$
By using one of the keywords FLOAT, INTEGER or STRING immediately
after the command DIM and before the variable(s) are listed. The specified
type then applies to all variables listed (ie, it does not have to be repeated).
For example:
DIM AS STRING first_name, last_name, city
Page 43
expressions surrounded by
brackets is used.
Examples:
DIM nbr(50)
DIM INTEGER nbr(50)
DIM name AS STRING
DIM a, b$, nbr(100), str$(20)
DIM a(5,5,5), b(1000)
DIM str$(200) LENGTH 20
DIM STRING str(200)
LENGTH 20
DIM a = 1234, b = 345
DIM STRING str = "text"
DIM x%(3) = (11, 22, 33, 44)
By using the Microsoft convention of using the keyword "AS" and the type
keyword (ie, FLOAT, INTEGER or STRING) after each variable. If you
use this method the type must be specified for each variable and can be
changed from variable to variable.
For example:
DIM amount AS FLOAT, name AS STRING
Floating point or integer variables will be set to zero when created and
strings will be set to an empty string (ie, ""). You can initialise the value of
the variable with something different by using an equals symbol (=) and an
expression following the variable definition. For example:
DIM AS STRING city = "Perth", house = "Brick"
The initialising value can be an expression (including other variables) and
will be evaluated when the DIM command is executed. See the section
"Defining and Using Variables" for more examples of the syntax.
As well as declaring simple variables the DIM command will also declare
arrayed variables (ie, an indexed variable with a number of dimensions).
Following the variable's name the dimensions are specified by a list of
numbers separated by commas and enclosed in brackets. For example:
DIM array(10, 20)
Each number specifies the number of elements in each dimension. Normally
the numbering of each dimension starts at 0 but the OPTION BASE
command can be used to change this to 1.
The above example specifies a two dimensional array with 11 elements (0 to
10) in the first dimension and 21 (0 to 20) in the second dimension. The
total number of elements is 231 and because each floating point number
requires 4 bytes a total of 924 bytes of memory will be allocated (integers
are different and require 8 bytes per element).
Strings will default to allocating 255 bytes (eg, characters) of memory for
each element and this can quickly use up memory. In that case the
LENGTH keyword can be used to specify the amount of memory to be
allocated to each element and therefore the maximum length of the string
that can be stored. This allocation ('n') can be from 1 to 255 characters.
For example: DIM str$(5, 10) will declare a string array with 66 elements
consuming 16,896 bytes of memory while:
DIM AS STRING str (5, 10) LENGTH 20
Will only consume 1,386 bytes of memory. Note that the amount of
memory allocated for each element is n + 1 as the extra byte is used to track
the actual length of the string stored in each element.
If a string longer than 'n' is assigned to an element of the array an error will
be produced. Other than this string arrays created with the LENGTH
keyword act exactly the same as other string arrays. Note that the LENGTH
keyword can also be used when defining non array string variables.
In the above example you can also use the Microsoft syntax of specifying the
type after the length specifier. For example:
DIM str (5, 10) LENGTH 20 AS STRING
Arrays can also be initialised when they are declared by adding an equals
symbol (=) followed by a bracketed list of values at the end of the
declaration. For example:
DIM INTEGER nbr(4) = (22, 44, 55, 66, 88)
or
DIM str$(3) = ("foo", "boo", "doo", "zoo")
Note that the number of initialising values must match the number of
elements in the array including the base value set by OPTION BASE. If a
multi dimensioned array is initialised then the first dimension will be
Page 44
This structure will loop forever; the EXIT command can be used to
terminate the loop or control must be explicitly transferred outside of the
loop by commands like GOTO or RETURN (if in a subroutine).
DO WHILE expression
<statements>
LOOP
Loops while "expression" is true (this is equivalent to the older WHILEWEND loop, also implemented in MMBasic). If, at the start, the expression
is false the statements in the loop will not be executed, even once.
DO
<statements>
LOOP UNTIL expression
Loops until the expression following UNTIL is true. Because the test is
made at the end of the loop the statements inside the loop will be executed at
least once, even if the expression is false.
EDIT
Page 45
use the arrow keys to highlight text which can be deleted, cut to the
clipboard or simply copied to the clipboard. The status line will change to
indicate the new functions of the function keys.
The editor will work with lines wider than the screen but characters beyond
the screen edge will not be visible. You can split such a line by inserting a
new line character and the two lines can be later rejoined by deleting the
inserted new line character.
Note that the program is edited in RAM which limits its size to 53K.
ELSE
ENDIF
or
END IF
END
END FUNCTION
Marks the end of a user defined function. See the FUNCTION command.
Each function must have one and only one matching END FUNCTION
statement. Use EXIT FUNCTION if you need to return from a function
from within its body.
END SUB
Marks the end of a user defined subroutine. See the SUB command.
Each sub must have one and only one matching END SUB statement. Use
EXIT SUB if you need to return from a subroutine from within its body.
ERROR [error_msg$]
EXIT DO
EXIT FOR
EXIT FUNCTION
EXIT SUB
Initiates a FOR-NEXT loop with the 'counter' initially set to 'start' and
incrementing in 'increment' steps (default is 1) until 'counter' equals 'finish'.
The increment must be an integer, but may be negative in which case the
loop will count downwards.
See also the NEXT command.
Page 46
The argument can also be another defined function or the same function if
recursion is to be used (the recursion stack is limited to 50 nested calls).
To set the return value of the function you assign the value to the function's
name. For example:
FUNCTION SQUARE(a)
SQUARE = a * a
END FUNCTION
Every definition must have one END FUNCTION statement. When this is
reached the function will return its value to the expression from which it was
called. The command EXIT FUNCTION can be used for an early exit.
You use the function by using its name and arguments in a program just as
you would a normal MMBasic function. For example:
PRINT SQUARE(56.8)
When the function is called each argument in the caller is matched to the
argument in the function definition. These arguments are available only
inside the function.
Functions can be called with a variable number of arguments. Any omitted
arguments in the function's list will be set to zero or a null string.
Arguments in the caller's list that are a variable (ie, not an expression or
constant) will be passed by reference to the function. This means that any
changes to the corresponding argument in the function will also be copied to
the caller's variable. Arrays are passed by specifying the array name with
empty brackets (eg, arg()) and are always passed by reference.
You must not jump into or out of a function using commands like GOTO,
GOSUB, etc. Doing so will have undefined side effects including the
possibility of ruining your day.
GOSUB target
Initiates a subroutine call to the target, which can be a line number or a label.
The subroutine must end with RETURN.
GOTO target
Evaluates the expression expr' and performs the THEN statement if it is true
or skips to the next line if false. The optional ELSE statement is the reverse
of the THEN test. This type of IF statement is all on one line.
The THEN statement construct can be also replaced with:
GOTO linenumber | label.
IF expression THEN
<statements>
[ELSE
<statements>]
[ELSEIF expression THEN
<statements>]
ENDIF
Multiline IF statement with optional ELSE and ELSEIF cases and ending
with ENDIF. Each component is on a separate line.
Evaluates 'expression' and performs the statement(s) following THEN if the
expression is true or optionally the statement(s) following the ELSE
statement if false.
The ELSEIF statement (if present) is executed if the previous condition is
false and it starts a new IF chain with further ELSE and/or ELSEIF
statements as required.
One ENDIF is used to terminate the multiline IF.
Page 47
Allows input from the console to a list of variables. The input command will
prompt with a question mark (?).
The input must contain commas to separate each data item if there is more
than one variable.
For example, if the command is: INPUT a, b, c
And the following is typed on the keyboard: 23, 87, 66
Then a = 23 and b = 87 and c = 66
If the "prompt string$" is specified it will be printed before the question
mark. If the prompt string is terminated with a comma (,) rather than the
semicolon (;) the question mark will be suppressed.
INPUT #nbr,
list of variables
Same as above except that the input is read from a serial port previously
opened for INPUT as nbr. See the OPEN command.
IRETURN
Returns from an interrupt that used a line number or label. The next
statement to be executed will be the one that was about to be executed when
the interrupt was detected.
Note that IRETURN must not be used where the interrupt routine is a user
defined subroutine. In that case END SUB or EXIT SUB should be used.
Page 48
r1, r2, r3 and r4 are pin numbers used for the four row connections to the
keypad and c1, c2, c3 and c4 are the column connections. c4 is optional and
is only used with 4x4 keypads. This command will automatically configure
these pins as required.
On a key press the value assigned to 'var' is the number of a numeric key (eg,
'6' will return 6) or 10 for the * key and 11 for the # key. On 4x4 keypads
the number 20 will be returned for A, 21 for B, 22 for C and 23 for D.
The KEYPAD CLOSE command will terminate the keypad function and
return the I/O pin to a not configured state.
See the section "Special Hardware Devices" for more details.
LET variable = expression
Display text on an LCD character display module. This command will work
with most 1-line, 2-line or 4-line LCD modules that use the KS0066,
HD44780 or SPLC780 controller (however this is not guaranteed).
The LCD INIT command is used to initialise the LCD module for use. 'd4'
to 'd7' are the I/O pins that connect to inputs D4 to D7 on the LCD module
(inputs D0 to D3 should be connected to ground). 'rs' is the pin connected to
the register select input on the module (sometimes called CMD). 'en' is the
pin connected to the enable or chip select input on the module. The R/W
input on the module should always be grounded. The above I/O pins are
automatically set to outputs by this command.
When the module has been initialised data can be written to it using the LCD
command. 'line' is the line on the display (1 to 4) and 'pos' is the character
location on the line (the first location is 1). 'text$' is a string containing the
text to write to the LCD display.
'pos' can also be C8, C16, C20 or C40 in which case the line will be cleared
and the text centred on a 8 or 16, 20 or 40 line display. For example:
LCD 1, C16, "Hello"
LCD CLEAR will erase all data displayed on the LCD and LCD CLOSE
will terminate the LCD function and return all I/O pins to the not configured
state.
See the section "Special Hardware Devices" for more details.
These commands will send one or more bytes to an LCD display as either a
command (LCD CMD) or as data (LCD DATA). Each byte is a number
between 0 and 255 and must be separated by commas. The LCD must have
been previously initialised using the LCD INIT command (see above).
These commands can be used to drive a non standard LCD in "raw mode" or
they can be used to enable specialised features such as scrolling, cursors and
custom character sets. You will need to refer to the data sheet for your LCD
to find the necessary command and data values.
Reads entire line from the serial console input into string-variable$. If
specified the prompt$ will be printed first. Unlike INPUT, LINE INPUT
will read a whole line, not stopping for comma delimited data items.
A question mark is not printed unless it is part of prompt$.
Same as above except that the input is read from a serial communications
port previously opened for INPUT as nbr. See the OPEN command.
LIST
or
LIST ALL
Page 49
MEMORY
NEW
NEXT [counter-variable] [,
counter-variable], etc
ON KEY target
Setup an interrupt which will call 'target' line number, label or user defined
subroutine whenever there is one or more characters waiting in the serial
console input buffer.
Return from an interrupt is via the IRETURN statement except where a user
defined subroutine is used (in that case END SUB or EXIT SUB is used).
Note that subroutine parameters cannot be used.
Note that all characters waiting in the input buffer should be read in the
interrupt routine otherwise another interrupt will be automatically generated
as soon as the program returns from the interrupt.
To disable this interrupt, use numeric zero for the target, ie: ON KEY 0
Will open a serial communications port for reading and writing. Two ports
are available (COM1: and COM2:) and both can be open simultaneously.
For a full description with examples see Appendix A.
Using fnbr the port can be written to and read from using any command or
function that uses a file number.
Page 50
OPTION BASE 0 | 1
Set the baud rate for the console to 'nbr'. This change is made immediately
and will be remembered even when the power is cycled. The baud rate
should be limited to the speeds listed in Appendix A for COM1.
Using this command it is possible to set the console to an unworkable baud
rate and in this case MMBasic should be reset as described in the section
"Resetting MMBasic". This will reset the baud rate to the default of 38400.
OPTION BREAK nn
Set the value of the break key to the ASCII value 'nn'. This key is used to
interrupt a running program.
The value of the break key is set to CTRL-C key at power up but it can be
changed to any keyboard key using this command (for example, OPTION
BREAK 4 will set the break key to the CTRL-D key).
Setting this option to zero will disable the break function entirely.
OPTION CASE
UPPER | LOWER | TITLE
Change the case used for listing command and function names when using
the LIST command. The default is TITLE but the old standard of MMBasic
can be restored using OPTION CASE UPPER.
This option will be remembered even when the power is removed.
OPTION CLOCKTRIM n
Trim the frequency of the internal oscillator which is used as the basis for all
timing (eg, date, time, pause, PWM frequency, serial baudrate, etc). 'n' is the
trim value which can range from -31 to +31 (this equates to an adjustment
range of about -12.5% to +12.5%). On power up the trim value is zero.
Note that this will also affect the console baudrate and an excessive trim
value could make it impossible to communicate with the Micromite.
Used to set the default type for a variable which is not explicitly defined.
If OPTION DEFAULT NONE is used then all variables must have their type
explicitly defined.
When a program is run the default is set to FLOAT for compatibility with
previous versions of MMBasic.
Page 51
Set the characteristics of the display terminal used for the console. Both the
LIST and EDIT commands need to know this information to correctly
format the text for display.
'lines' is the number of lines on the display and 'chars' is the width of the
display in characters. The default is 24 lines x 80 chars and when changed
this option will be remembered even when the power is removed.
Note that the documentation for the VT100 ASCII Video Terminal initially
listed incorrect specifications for the composite video. If you are using this
project with the Micromite check the website http://geoffg.net/terminal.html
for the correct specifications.
OPTION EXPLICIT
Placing this command at the start of a program will require that every variable
be explicitly declared using the DIM command before it can be used in the
program.
This option is disabled by default when a program is run. If it is used it must
be specified before any variables are used.
Set 'nbr' as the PIN (Personal Identification Number) for access to the
console prompt. 'nbr' can be any non zero number of up to eight digits.
Whenever a running program tries to exit to the command prompt for
whatever reason MMBasic will request this number before the prompt is
presented. This is a security feature as without access to the command
prompt an intruder cannot list or change the program in memory or modify
the operation of MMBasic in any way. To disable this feature enter zero for
the PIN number (ie, OPTION PIN 0).
A permanent lock can be applied by using 99999999 for the PIN number.
If a permanent lock is applied or the PIN number is lost the only way to
recover is to reset MMBasic as described in the section "Resetting
MMBasic" (this will also erase the program memory).
OPTION TAB 2 | 4 | 8
PAUSE delay
Halt execution of the running program for delay mS. This can be a
fraction. For example, 0.2 is equal to 200 S. The maximum delay is
2147483647 mS (about 24 days).
Note that interrupts will be recognised and processed while the pause is
operating.
For a pin configured as digital output this will set the output to low
(value is zero) or high (value non-zero). You can set an output high or
low before it is configured as an output and that setting will be the default
output when the SETPIN command takes effect.
See the function PIN() for reading from a pin and the command SETPIN for
configuring it. Refer to the section "Using the I/O pins" for a general
description of the Micromite's input/output capabilities.
Will set a byte or a word within the PIC32 virtual memory space.
POKE BYTE will set the byte (ie, 8 bits) at the memory location 'addr%' to
'byte'. 'addr%' should be an integer.
POKE WORD will set the word (ie, 32 bits) at the memory location 'addr%'
to 'word%'. 'addr%' and 'word%' should be integers.
POKE VAR will set a byte in the memory address of 'var'. 'offset' is the
offset from the address of the variable. An array is specified as var().
POKE VARTBL will set a byte in MMBasic's variable table. 'offset' is the
offset from the start of the variable table. Note that a comma is required
after the keyword VARTBL.
For backwards compatibility the old form of POKE hiword, loword, val is
still accepted. In this case the address is specified by hiword which is the
Page 52
PRINT expression
[[,; ]expression] etc
Outputs text to the serial console. Multiple expressions can be used and must
be separated by either a:
Comma (,) which will output the tab character
Semicolon (;) which will not output anything (it is just used to separate
expressions).
Nothing or a space which will act the same as a semicolon.
A semicolon (;) at the end of the expression list will suppress the automatic
output of a carriage return/ newline at the end of a print statement.
When printed, a number is preceded with a space if positive or a minus (-) if
negative but is not followed by a space. Integers (whole numbers) are
printed without a decimal point while fractions are printed with the decimal
point and the significant decimal digits. Large floating point numbers
(greater than six digits) are printed in scientific number format.
The function TAB() can be used to space to a certain column and the string
functions can be used to justify or otherwise format strings.
Will generate a pulse on 'pin' with duration of 'width' mS. 'width' can be a
fraction. For example, 0.01 is equal to 10S and this enables the generation
of very narrow pulses. The minimum is 5S at 40MHz to 40S at 5MHz.
The generated pulse is of the opposite polarity to the state of the I/O pin
when the command is executed. For example, if the output is set high the
PULSE command will generate a negative going pulse. Notes:
'pin' must be configured as an output.
For a pulse of less than 3 mS the accuracy is 1 S.
For a pulse of 3 mS or more the accuracy is 0.5 mS.
A pulse of 3 mS or more will run in the background. Up to five different
and concurrent pulses can be running in the background and each can
have its time changed by issuing a new PULSE command or it can be
terminated by issuing a PULSE command with zero for 'width'.
PWM 1, freq, 1A
or
Page 53
pages 6 and 7 (they are also used for the SERVO command). Controller 1
can have one, two or three outputs while controller 2 can have one or two
outputs. Both controllers are independent and can be turned on and off and
have different frequencies.
'1' or '2' is the controller number and freq is the output frequency (between
20 Hz and 500KHz) . 1A, 1B and 1C are the duty cycle for each of the
controller 1 outputs while 2A and 2B are the duty cycle for the controller 2
outputs. The specified I/O pins will be automatically configured as outputs
while any others will be unaffected and can be used for other duties.
The duty cycle for each output is independent of the others and is specified
as a percentage. If it is close to zero the output will be a narrow positive
pulse, if 50 a square wave will be generated and if close to 100 it will be a
very wide positive pulse. For frequencies below 25 KHz the duty cycle will
be accurate to 0.1%.
The output will run continuously in the background while the program is
running and can be stopped using the STOP command. The frequency and
duty cycle can be changed at any time (without stoping the output) by
issuing a new PWM command.
The PWM function will take control of any specified outputs and when
stopped the pins will be returned to a high impedance "not configured" state.
RANDOMIZE nbr
Reads values from DATA statements and assigns these values to the named
variables. Variable types in a READ statement must match the data types in
DATA statements as they are read. See also DATA and RESTORE.
REM string
RESTORE
Resets the line and position counters for DATA and READ statements to the
top of the program file.
RETURN
RTC GETTIME
or
RTC SETTIME year, month,
day, hour, minute, second
or
RTC SETREG reg, value
or
RTC GETREG reg, var
RTC GETTIME will get the current date/time from a PCF8563, DS1703,
DS3231 or DS3232 real time clock and set the internal MMBasic clock
accordingly. The date/time can then be retrieved with the DATE$ and
TIME$ functions.
RTC SETTIME will set the time in the clock chip. The year must be the last
two digits of the year (ie, 14 for 2014) and hour is 0 to 23 hours (ie, 24 hour
notation).
The RTC SETREG and GETREG commands can be used to set or read the
contents of registers within the chip. 'reg' is the register's number, 'value' is
the number to store in the register and 'var' is a variable that will receive the
number read from the register. These commands are not necessary for
normal operation but they can be used to manipulate special features of the
chip (alarms, output signals, etc). They are also useful for storing temporary
information in the chip's battery backed RAM.
These chips are I2C devices and must be connected to the two I2C pins with
appropriate pullup resistors. If the I2C bus is already open the RTC
command will use the current settings, otherwise it will temporarily open the
connection with a speed of 100KHz.
See the section "Special Hardware Devices" for more details.
Page 54
RUN
SELECT CASE value
CASE testexp [[, testexp] ]
<statements>
<statements>
CASE ELSE
<statements>
<statements>
END SELECT
Page 55
SERVO 1 [, freq], 1A
or
SERVO 1 [, freq], 1A, 1B
or
SERVO 1 [, freq], 1A, 1B, 1C
or
SERVO 2 [, freq], 2A
or
SERVO 2 [, freq], 2A, 2B
or
SERVO channel, STOP
Will configure an external I/O pin. Refer to the section "Using the I/O pins"
for a general description of the Micromite's input/output capabilities.
'pin' is the I/O pin to configure, cfg is the mode that the pin is to be set to
and 'option' is an optional parameter. 'cfg' is a keyword and can be any one
of the following:
OFF
Not configured or inactive
AIN
Analog input (ie, measure the voltage on the input)
DIN
Digital input
If 'option' is omitted the input will be high impedance
If 'option' is the keyword "PULLUP" an internal resistor will
be used to pull up the input pin to 3.3V If the keyword
"PULLDOWN" is used the pin will be pulled down to zero
volts. The value of the pull up or down is the equivalent of
about 100K.
FIN
Frequency input
'option' can be used to specify the gate time (the length of time
used to count the input cycles). It can be any number between
10mS and 100000mS. Note that the PIN() function will
always return the frequency correctly scaled in Hz regardless
of the gate time used. If 'option' is omitted the gate time will
be 1 second.
PIN
Period input
'option' can be used to specify the number of input cycles to
average the period measurement over. It can be any number
between 1 and 10000. Note that the PIN() function will
always return the average period of one cycle correctly scaled
in mS regardless of the number of cycles used for the average.
If 'option' is omitted the period of just one cycle will be used.
CIN
Counting input
DOUT
Digital output
'option' can be "OC" in which case the output will be open
Page 56
Page 57
or a null string.
Arguments in the caller's list that are a variable (ie, not an expression or
constant) will be passed by reference to the subroutine. This means that any
changes to the corresponding argument in the subroutine will also be copied
to the caller's variable and therefore may be accessed after the subroutine has
ended. Arrays are passed by specifying the array name with empty brackets
(eg, arg()) and are always passed by reference. Brackets around the
argument list in both the caller and the definition are optional.
TIME$ = "HH:MM:SS"
or
TIME$ = "HH:MM"
or
TIME$ = "HH"
Sets the time of the internal clock. MM and SS are optional and will default
to zero if not specified. For example TIME$ = "14:30" will set the clock to
14:30 with zero seconds.
The time is set to "00:00:00" on power up.
TIMER = msec
TROFF
TRON
Turns on the trace facility. This facility will print the number of each line
(counting from the beginning of the program) in square brackets as the
program is executed. This is useful in debugging programs.
VAR SAVE will save one or more variables to non volatile flash memory
where they can be restored later (normally after a power interruption).
'var' can be any number of numeric or a string variables. When this
command is run any previously saved variables are automatically erased
first. Therefore all the variables that need to be saved must be listed on the
one command line.
VAR RESTORE will retrieve the previously saved variables and insert them
(and their values) into the variable table.
This command is normally used to save calibration data, options, and other
data which does not change often but needs to be retained across a power
interruption. Normally the VAR RESTORE command is placed at the start
of the program so that previously saved variables are restored and
immediately available to the program when it starts.
Notes:
Arrays cannot be saved with this command.
The storage space available to this command is 2KB.
If, when using RESTORE, a variable with the same name already exists
its value will be overwritten.
Using VAR RESTORE without a previous save will have no effect and
will not generate an error.
The saved data can be erased by using VAR SAVE without any
arguments, or by the NEW command or by following the procedure
described in the section "Resetting MMBasic".
WATCHDOG timeout
or
WATCHDOG OFF
Starts the watchdog timer which will automatically restart the processor
when it has timed out. This can be used to recover from some event that
disabled the running program (such as an endless loop or a programming or
other error that halts a running program). This can be important in an
unattended control situation.
'timeout' is the time in milliseconds (mS) before a restart is forced. This
command should be placed in strategic locations in the running BASIC
program to constantly reset the timer and therefore prevent it from counting
down to zero.
Page 58
If the timer count does reach zero (perhaps because the BASIC program has
stopped running) the PIC32 processor will be automatically restarted and the
automatic variable MM.WATCHDOG will be set to true (ie, 1) indicating
that an error occurred. On a normal startup MM.WATCHDOG will be set to
false (ie, 0).
At any time WATCHDOG OFF can be used to disable the watchdog timer
(this is the default on a reset or power up). The timer is also turned off when
the break character (normally CTRL-C) is used on the console to interrupt a
running program.
XMODEM SEND
or
XMODEM RECEIVE
Page 59
Functions
Detailed Listing
Note that the functions related to communications functions (I2C, 1-Wire, and SPI) are not listed here but are
described in the appendices at the end of this document.
Square brackets indicate that the parameter or characters are optional.
ABS( number )
Returns the absolute value of the argument 'number' (ie, any negative sign is
removed and the positive number is returned).
ASC( string$ )
Returns the ASCII code for the first letter in the argument string$.
ATN( number )
Returns a string giving the binary (base 2) value for the 'number'.
'chars' is optional and specifies the number of characters in the string with
zero as the leading padding character(s).
CHR$( number )
CINT( number )
COS( number )
DATE$
Returns the current date based on MMBasics internal clock as a string in the
form "DD-MM-YYYY". For example, "28-07-2012".
The internal clock/calendar will keep track of the time and date including
leap years. To set the date use the command DATE$ =.
DEG( radians )
Page 60
DS18B20( pin )
EOF( [#]nbr )
For a serial communications port this function will return true if there are no
characters waiting in the receive buffer.
The # is optional. Also see the OPEN, INPUT and LINE INPUT commands
and the INPUT$ function.
EXP( number )
FIX( number )
Returns a string giving the hexadecimal (base 16) value for the 'number'.
'chars' is optional and specifies the number of characters in the string with
zero as the leading padding character(s).
INKEY$
Checks the console input buffers and, if there is one or more characters
waiting in the queue, will remove the first character and return it as a single
character in a string.
If the input buffer is empty this function will immediately return with an
empty string (ie, "").
INPUT$(nbr, [#]fnbr)
Page 61
INT( number )
Truncate an expression to the next whole number less than or equal to the
argument. For example 9.89 will return 9 and -2.11 will return -3.
This behaviour is for Microsoft compatibility, the FIX() function provides a
true integer function.
See also CINT() .
LEN( string$ )
LOC( [#]fnbr )
For a serial communications port opened as 'fnbr' this function will return the
number of bytes received and waiting in the receive buffer to be read.
The # is optional.
LOF( [#]fnbr )
For a serial communications port opened as 'fnbr' this function will return the
space (in characters) remaining in the transmit buffer. Note that when the
buffer is full MMBasic will pause when adding a new character and wait for
some space to become available.
The # is optional.
LOG( number )
LCASE$( string$ )
PEEK(BYTE addr%)
or
PEEK(WORD addr%)
or
PEEK(VARADDR var)
or
PEEK(CFUNADDR cfun)
or
PEEK(VAR var, offset)
or
PEEK( VARTBL, offset)
or
PEEK( PROGMEM, offset)
Will return a byte or a word within the PIC32 virtual memory space.
BYTE will return the byte (8-bits) located at 'addr%'
WORD will return the word (32-bits) located at 'addr%'
VARADDR will return the address (32-bits) of the variable 'var' in memory.
An array is specified as var().
CFUNADDR will return the address (32-bits) of the CFunction 'cfun' in
memory. This address can be passed to another CFunction which can then
call it to perform some common process.
VAR, will return a byte in the memory allocated to 'var'. An array is
specified as var().
VARTBL, will return a byte in the memory allocated to the variable table
maintained by MMBasic. Note that there is a comma after the keyword
VARTBL.
PROGMEM, will return a byte in the memory allocated to the program.
Note that there is a comma after the keyword PROGMEM.
Note that 'addr%' should be an integer.
For backwards compatibility PEEK( hiword, loword ) is still accepted. In
this case the address is specifies by hiword which is the top 16 bits of the
Page 62
PIN( pin )
Returns the value on the external I/O pin. Zero means digital low, 1 means
digital high and for analogue inputs it will return the measured voltage as a
floating point number.
Frequency inputs will return the frequency in Hz. A period input will return
the period in milliseconds while a count input will return the count since
reset (counting is done on the positive rising edge). The count input can be
reset to zero by resetting the pin to counting input (even if it is already so
configured).
Pin zero is a special case. Using a pin number of zero will return the
measured voltage of the internal 1.2V reference inside the Micromite.
Also see the SETPIN and PIN() = commands. Refer to the section "Using
the I/O pins" for a general description of the Micromite's input/output
capabilities.
POS
Page 63
RAD( degrees )
RND( number )
SGN( number )
Returns the sign of the argument 'number', +1 for positive numbers, 0 for 0,
and -1 for negative numbers.
SIN( number )
SPACE$( number )
SQR( number )
STR$( number )
or
STR$( number, m )
or
STR$( number, m, n )
or
STR$( number, m, n, c$ )
Returns a string 'nbr' bytes long consisting of either the first character of
string$ or the character representing the ASCII value 'ascii' which is a
decimal number in the range of 32 to 126.
TAB( number )
Outputs spaces until the column indicated by 'number' has been reached.
TAN( number )
TIME$
Returns the current time based on MMBasic's internal clock as a string in the
form "HH:MM:SS" in 24 hour notation. For example, "14:30:00".
To set the current time use the command TIME$ = .
Page 64
TIMER
Returns the elapsed time in milliseconds (eg, 1/1000 of a second) since reset.
The timer is reset to zero on power up or a CPU restart and you can also
reset by using TIMER as a command. If not specifically reset it will
continue to count up forever.
UCASE$( string$ )
VAL( string$ )
Page 65
SPC( number )
WHILE expression
WEND
Page 66
Baud Rate
COM1: is implemented using the onboard UART in the PIC32 while COM2: is implemented in software and
therefore cannot run as fast. The maximum speed for both COM ports is limited by the CPU's speed as listed
below (the CPU speed can be changed with the CPU SPEED command):
CPU Speed
COM1: Maximum
COM2: Maximum
48 MHz
40 MHz (default)
30 MHz
20 MHz
10 MHz
5 MHz
282000
230400
115200
115200
57600
38400
19200
19200
9600
9600
4800
2400
Note that below these limits any baud rate can be chosen, for example 1111 bps is a valid speed for both ports.
Page 67
Examples
Opening a serial port using all the defaults:
OPEN "COM2:" AS #2
Opening a serial port specifying only the baud rate (4800 bits per second):
OPEN "COM2:4800" AS #1
Opening a serial port specifying the baud rate (9600 bits per second) and receive buffer size (1KB):
OPEN "COM1:9600, 1024" AS #8
An example specifying everything including an interrupt, an interrupt level, inverted and two stop bits:
OPEN "COM1:19200, 1024, ComIntLabel, 256, INV, S2" AS #5
Interrupts
The interrupt routine (if specified) will operate the same as a general interrupt on an external I/O pin (see
page 7 for a description). Return from the interrupt is via the IRETURN statement except where a user defined
subroutine is used (in that case END SUB or EXIT SUB is used). Note that subroutine parameters cannot be
used.
When using interrupts you need to be aware that it will take some time for MMBasic to respond to the interrupt
and more characters could have arrived in the meantime, especially at high baud rates. So, for example, if you
have specified the interrupt level as 200 characters and a buffer of 256 characters then quite easily the buffer
will have overflowed by the time the interrupt routine can read the data. In this case the buffer should be
increased to 512 characters or more.
Page 68
IEEE 485
The 'DE' option in the OPEN comspec$ for COM1: specifies that the Data output Enable (ENABLE) signal for
the IEEE 485 protocol will be generated. This signal will appear on pin 7 on the 28-pin chip and is normally
high. Just before a byte is transmitted this output will go low and when the byte has finished transmission the
output will go high again. Note that this polarity is the opposite of that used in the Maximite family and an
inverter is normally required to drive the DE input of an IEEE 485 transceiver.
Many IEEE 485 systems also use 9 bits of data for transmit and receive. The 9th bit is used to indicate that an
address is being sent or received. To accommodate this the '9BIT' option in the OPEN comspec$ for COM1:
can be used. With this option all data sent must be sent in pairs of bytes the first byte is the 9th bit and the
second is the data (the other 8 bits). The first byte should be either the ASCII character '1' to indicate that the
9th bit should be set or '0' for not set. This 9th bit is then applied to the second byte in the pair and together they
represent the 9 bits of data to send.
For example, the following fragment of code will send three 9 bit data items. The first is an address (bit 9 is
high) and the second two are the data (bit 9 is low):
OPEN "COM1:
PRINT "1" +
PRINT "0" +
PRINT "0" +
4800, 9BIT" as #1
CHR$(211);
CHR$(23);
CHR$(0);
Note that in the PRINT commands the automatic CR/LF is suppressed by the use of the semicolon.
Received data is similar. The 9bit data is translated into two characters the first is the ASCII character '1' or
'0' indicating the state of the 9th bit in the data received and the second character is the other 8 bits. This means
that a BASIC program must read the data as pairs and apply logic to determine the value of the 9th bit (the first
character) and then take the appropriate action with the second character.
For example:
IF LOC(#1) >= 2 THEN
' check that we have at least two bytes
A$ = INPUT$(1, #1) : B$ = INPUT$(1, #1)
IF A$ = "1" THEN
' B$ contains an address
ELSE
' B$ contains some data
ENDIF
ENDIF
MMBasic does not check that data is printed or read to/from the COM port in pairs. If your program
inadvertently sends or reads a single character it will disrupt all subsequent communications.
Note also that in 9 bit mode the size of the transmit and receive buffers are effectively halved because each
9 bit data item is stored as two bytes.
Page 69
These measures break the rules for RS-232 signalling, but if you only want to use it over a short distance (a
metre or two) it should work fine.
To summarise, use this circuit (the pin numbers are for a 28-pin chip):
Page 70
I2C CLOSE
Disables the slave I2C module and returns the I/O pins to a "not configured"
state. Then can then be configured using SETPIN. This command will also
send a stop if the bus is still held.
Page 71
And similarly there are four commands for the slave mode:
I2C SLAVE OPEN addr,
mask, option, send_int,
rcv_int
Send the data to the I2C master. This command should be used in the send
interrupt (ie in the 'send_int_line' when the master has requested data).
Alternatively a flag can be set in the send interrupt routine and the command
invoked from the main program loop when the flag is set.
sendlen is the number of bytes to send.
senddata is the data to be sent. This can be specified in various ways, see
the I2C WRITE commands for details.
Receive data from the I2C master device. This command should be used in
the receive interrupt (ie in the 'rcv_int_line' when the master has sent some
data). Alternatively a flag can be set in the receive interrupt routine and the
command invoked from the main program loop when the flag is set.
rcvlen is the maximum number of bytes to receive.
rcvbuf is the variable to receive the data - this can be a string variable (eg,
t$), or a one dimensional array of numbers specified without the dimensions
(eg, data()) or a normal numeric variable (in this case rcvlen must be 1).
rcvd will contain the actual number of bytes received by the command.
Disables the slave I2C module and returns the external I/O pins 12 and 13 to
a "not configured" state. Then can then be configured using SETPIN.
Following an I2C write or read command the automatic variable MM.I2C will be set to indicate the result of the
operation as follows:
0 = The command completed without error.
1 = Received a NACK response
2 = Command timed out
For users of MMBasic on earlier devices
This implementation of the I2C protocol is generally compatible with previous versions with the following
differences:
The commands have been renamed but have the same functionality. I2CEN is now I2C OPEN,
I2CSEND is I2C WRITE, I2CRCV is I2C READ and I2CDIS is now I2C CLOSE. Similarly, I2CSEN
is now I2C SLAVE WRITE, etc.
Master interrupts are not supported.
The NUM2BYTE command and BYTE2NUM () function are not implemented (use the PEEK function
and POKE command instead).
Page 72
10 Bit Addressing
10-bit addressing was designed to be compatible with 7-bit addresses, allowing developers to mix the two types
of devices on a single bus. Devices that use 10-bit addresses will be clearly identified as such in their data
sheets.
In 10-bit addressing the slave address is sent in two bytes with the first byte beginning with a special bit pattern
to indicate that a 10 bit address is being used. This process is automatically managed by MMBasic when the
'option' argument is set for 10-bit addressing. 10-bit addresses can be in the range of 0 to 3FF (hex).
Master/Slave Modes
The master and slave modes can be enabled simultaneously; however, once a master command is in progress,
the slave function will be "idle" until the master releases the bus. Similarly, if a slave command is in progress,
the master commands will be unavailable until the slave transaction completes.
In master mode, the I2C send and receive commands will not return until the command completes or a timeout
occurs (if the timeout option has been specified).
The slave mode uses an MMBasic interrupt to signal a change in status and in this routine the Micromite should
write/read the data as specified by the I2C master. This operates the same as a general interrupt on an external
I/O pin. Return from the interrupt is via the IRETURN statement except where a user defined subroutine is
used (in that case END SUB or EXIT SUB is used).
I/O Pins
On a 28-pin chip pin 18 becomes the I2C data line (SDA) and pin 17 the clock (SCL). On a 44-pin chip pin 1
becomes the I2C data line (SDA) and pin 44 the clock (SCL).
Both of these pins should have external pullup resistors installed (typical values are 10K for 100KHz or 2K
for 400 kHz). When the I2C CLOSE command is used the I/O pins are reset to a "not configured" state. Then
can then be configured as per normal using SETPIN.
When running the I2C bus at above 150 kHz the cabling between the devices becomes important. Ideally the
cables should be as short as possible (to reduce capacitance) and also the data and clock lines should not run
next to each other but have a ground wire between them (to reduce crosstalk).
If the data line is not stable when the clock is high, or the clock line is jittery, the I2C peripherals can get
"confused" and end up locking the bus (normally by holding the clock line low). If you do not need the higher
speeds then operating at 100 kHz is the safest choice.
Example
I2C is ideally suited for communications between integrated circuits. As an example, there might be an
occasion when a single Micromite or Maximite does not have enough serial ports, I/O pins, or whatever for a
particular application. In that case a Micromite could be used as a slave to provide the extra facilities.
This example converts a Micromite into a general purpose I/O expansion chip with 17 I/O pins that can be
dynamically configured (by the master) as analog inputs or digital input/outputs. The routines on the master are
simple to use (SSETPIN to configure the slave I/O and SPIN() to control it) and the program running on the
master need not know that the physical I/O pins reside on another chip. All communications are done via I2C.
Page 73
Additional Input/Outputs
The following illustration shows the connections required for 28-pin chips:
Page 74
WATCHDOG 1000
LOOP
ReadD:
I2C SLAVE READ 3, msg(), recvd
IF msg(0) = 1 THEN
SETPIN msg(1), msg(2)
ELSEIF msg(0) = 2 THEN
PIN(msg(1)) = msg(2)
ELSE
s$ = str$(pin(msg(1))) + Space$(12)
ENDIF
IRETURN
'
'
'
'
'
'
'
'
received a message
get the message into the array
command = 1
configure the I/O pin
command = 2
set the I/O pin's output
the command must be 3
get the input on the I/O pin
WriteD:
I2C SLAVE WRITE 12, s$
IRETURN
This subroutine will set the output of the slave's pin to 'output' (ie, high or low).
nn = SPIN(pin)
This function will return the value of the input on the slave's I/O pin.
For example, to display the voltage on pin 3 of the slave you would use:
SSETPIN 3, 1
PRINT SPIN(3)
As another example, to flash a LED connected to pin 15 of the slave you would use:
SSETPIN 15, 8
SPIN 15, 1
PAUSE 300
SPIN 15, 0
These are the three routines:
' configure an I/O pin on the slave
SUB SSETPIN pinnbr, cfg
I2C OPEN 100, 1000
I2C WRITE &H26, 0, 3, 1, pinnbr, cfg
IF MM.I2C THEN ERROR "Slave did not respond"
I2C CLOSE
END SUB
Page 75
Page 76
Where:
pin - The Micromite I/O pin to use. It can be any pin capable of digital I/O.
flag - A combination of the following options:
1 - Send reset before command
2 - Send reset after command
4 - Only send/recv a bit instead of a byte of data
8 - Invoke a strong pullup after the command (the pin will be set high and open drain disabled)
length - Length of data to send or receive
data - Data to send or variable to receive.
The number of data items must agree with the length parameter.
And the automatic variable
MM.ONEWIRE
Page 77
I/O Pins
The SPI OPEN command will automatically configure the relevant I/O pins. For 28-pin chips pin 25 will
become the clock output, pin 14 will be the data in (MISO) and pin 3 will become the data out (MOSI). For
44-pin chips pin 14 is the clock, pin 41 the data in and pin 20 the data out.
When the SPI CLOSE command is used these pins will be returned to a "not configured" state. They can then
be configured as per normal using SETPIN.
An SPI enable signal is often used to select a slave and "prime" it for data transfer. This signal is not generated
by this function and (if required) should be generated using the PIN function on another pin.
SPI Open
To use the SPI function the SPI channel must be first opened (this is different from previous versions of
MMBasic). The syntax for opening the SPI channel is:
SPI OPEN speed, mode, bits
Where:
speed is the speed of the clock. It is a number representing the clock speed in Hz. The maximum is
one quarter the CPU speed (ie, 10000000 at a CPU speed of 40MHz).
'mode' is a single numeric digit representing the transmission mode see Transmission Format below.
'bits' is the number of bits to send/receive. This can be 8, 16 or 32.
Standard Send/Receive
When the SPI channel is open data can be sent and received using the SPI function. The syntax is:
received_data = SPI(data_to_send)
Note that a single SPI transaction will send data while simultaneously receiving data from the slave.
data_to_send is the data to send and the function will return the data received during the transaction. If you
do not want to send any data (ie, you wish to receive only) any number (eg, zero) can be used for the data to
send. Similarly if you do not want to use the data received it can be assigned to a variable and ignored.
Bulk Send/Receive
Data can also be sent in bulk:
SPI WRITE nbr, data1, data2, data3, etc
or
SPI WRITE nbr, string$
or
SPI WRITE nbr, array()
In the first method 'nbr' is the number of data items to send and the data is the expressions in the argument list
(ie, 'data1', data2' etc).
In the second or third method listed above the data to be sent is contained in the 'string$' or the contents of
'array()' (which must be a single dimension array of integer or floating point numbers). The string length, or the
size of the array must be the same or greater than nbr. Any data returned from the slave is discarded.
Data can also be received in bulk:
SPI READ nbr, array()
Where 'nbr' is the number of data items to be received and array() is a single dimension integer array where the
received data items will be saved. This command sends zeros while reading the data from the slave.
SPI Close
If required the SPI communications channel can be closed as follows (the I/O pins will be set to inactive):
SPI CLOSE
Page 78
Transmission Format
The most significant bit is sent and received first. The format of the transmission can be specified by the 'mode'
as shown below. Mode 3 is the most common format.
Mode
Description
CPOL
CPHA
Clock is active high, data is captured on the rising edge and output on the falling edge
Clock is active high, data is captured on the falling edge and output on the rising edge
Clock is active low, data is captured on the falling edge and output on the rising edge
Clock is active low, data is captured on the rising edge and output on the falling edge
Examples
The following example will send the command 80 (hex) and receive two bytes from the slave SPI device using
the standard send/receive function:
PIN(10) = 1 : SETPIN 10, DOUT
SPI OPEN 5000000, 3, 8
PIN(10) = 0
junk = SPI(&H80)
byte1 = SPI(0)
byte2 = SPI(0)
PIN(10) = 1
SPI CLOSE
'
'
The following is similar to the example given above but this time the transfer is made using the bulk
send/receive commands:
OPTION BASE 1
DIM data%(2)
PIN(10) = 1 : SETPIN 10, DOUT
SPI OPEN 5000000, 3, 8
PIN(10) = 0
SPI WRITE 1, &H80
SPI READ 2, data%()
PIN(10) = 1
SPI CLOSE
'
'
'
'
Page 79