Home

Micromite Manual

image

Contents

1. function to get the SPI data FUNCTION ReadSPI SPI OPEN 4000000 0 8 4meg speed mode 0 8bits PIN 26 0 chip select low SPI write 3 3 0 0 send a command SPI read 1 ReadSPI and get the respons PIN 26 1 chip select high SPI CLOSE END FUNCTION Examples The following example shows how to use the SPI port for general I O It will send a command 80 hex and receive two bytes from the slave SPI device using the standard send receive function PIN 10 1 SETPIN 10 DOUT pin 10 will be used as the enable signal SPI OPEN 5000000 3 8 speed is 5MHz and the data size is 8 bits PIN 10 0 assert th nable line active low junk SPI amp H80 send the command and ignore the return bytel SPI 0 get the first byte from the slave byte2 SPI 0 get the second byte from the slave PIN 10 1 deselect the slav SPI CLOSE and close the channel Micromite User Manual Page 90 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 our array will start with the index 1 DIM data 2 define the array for receiving the data PIN 10 1 SETPIN 10 DOUT pin 10 will be used as the enable signal SPI OPEN 5000000 3 8 speed is 5MHz 8 bits data PIN 10 0 assert th nable line active low SPI WRITE 1 amp H80 send the command SPI READ 2 data
2. For example the following 64 bit unsigned operation will return the expected results X amp HFFFFOOOOFFFF0044 YS amp H800FFFFFFFFFFFFF X X AND Y PRINT HEXS INS 16 Will display 800F0000FFFF0044 Micromite User Manual Page 37 Using the I O pins Digital Inputs A digital input is the simplest type of input configuration If the input voltage is higher than 2 5V the logic level will be true numeric value of 1 and anything below 0 65V will be false numeric value of 0 The inputs use a Schmitt trigger input so anything in between these levels will retain the previous logic level Pins marked as 5V are 5V tolerant and can be directly connected to a circuit that generates up to 5V without the need for voltage dropping resistors In your BASIC program you would set the input as a digital input and use the PIN function to get its level For example SETPIN 23 DIN IF PIN 23 1 THEN PRINT High The SETPIN command configures pin 23 as a digital input and the PINQ function will return the value of that pin the number 1 if the pin is high The IF command will then execute the command after the THEN statement if the input was high If the input pin was low the program would just continue with the next line in the program The SETPIN command also recognises a couple of options that will connect an internal resistor from the input to either the supply or ground This is
3. 2 treat the address as a 10 bit address 3 combine and 2 hold the bus and use 10 bit addresses sendlen is the number of bytes to send senddata is the data to be sent this can be specified in various ways all values sent will be between 0 and 255 e The data can be supplied in the command as individual bytes Example I2C WRITE amp H6F 1 3 amp H23 amp H43 amp H25 e The data can be in a one dimensional array specified with empty brackets ie no dimensions The data will be written starting with the first element Example I2C WRITE amp H6F 1 3 ARRAY e The data can be a string variable not a constant Example I2C WRITE amp H6F 1 3 STRING I2C READ addr option Get data from the IC slave device revlen revbuf addr is the slave DC address option is a number between 0 and 3 normally this is set to 0 1 keep control of the bus after the command a stop condition will not be sent at the completion of the command 2 treat the address as a 10 bit address 3 combine and 2 hold the bus and use 10 bit addresses revlen is the 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 revlen must be 1 I2C CLOSE Disables the slave UC module and returns the I O pins to a not config
4. 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 top 16 bits of the address while loword is the bottom 16 bits This command is for expert users only The PIC32 maps all control registers flash program memory and volatile RAM memory into a single address space so there is no need for INP or OUT commands The PIC32 Data Sheet lists the details of this address space RAM starts at 0xA0000000 Micromite User Manual Page 63 PORT start nbr start nbr value Set a number of I O pins simultaneously ie with one command start is an I O pin number and the lowest bit in value bit 0 will be used to set that pin Bit 1 will be used to set the pin start plus 1 bit 2 will set pin start 2 and so on for nbr number of bits I O pins used must be numbered consecutively and any I O pin that is invalid or not configured as an output will cause an error The start nbr pair can be repeated if an additional group of output pins needed to be added Fo
5. get two bytes from the slave PIN 10 1 deselect the slav SPI CLOSE and close the channel Micromite User Manual Page 91
6. Quick Start Tutorial The following assumes that you have programmed MMBasic into a suitable microcontroller This can be done as shown previously or by buying a pre programmed chip 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 2 3 to 3 6V 26mA Can be 2 x AA batteries or a nominal 3 3V power supply Serial Console VT100 Terminal or USB to TTL Converter 38400 baud 8 bits no parity one stop bit TTL Voltage Levels J Data from Micromite 19 47uF 6v n Rx Km Ceramic or eria Tx Data to Micromite Tantalum Terminal Gnd 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
7. SEND and RECEIVE can be abbreviated to S and R The XModem protocol requires a cooperating software program running on the remote computer and connected to its serial port It has been tested on Tera Term running on Windows and it is recommended that this be used After running the XMODEM command in MMBasic select File gt Transfer gt XMODEM gt Receive Send from the Tera Term menu to start the transfer The transfer can take up to 15 seconds to start and if the XMODEM command fails to establish communications it will return to the MMBasic prompt after 60 seconds and leave the program memory untouched Download Tera Term from http ttssh2 sourceforge jp Micromite User Manual Page 70 Functions Note that the functions related to communications functions PC 1 Wire and SPT 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 ARC string Returns the ASCII code for the first letter in the argument string ATN number Returns the arctangent value of the argument number in radians BIN number chars 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
8. When the SPI channel is open data can be sent and received using the SPI or SPI2 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 dap o 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 on SPI or SPI2 SPI WRITE nbr datal data2 data3 etc or SPI WRITE nbr string or SPI WRITE nbr array Micromite User Manual Page 89 In the first method nbr is the number of data items to send and the data is the expressions in the argument list ie datal 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 on SPI or SPI2 SPI READ nbr array Where nbr is the number of data items to be received and array is a single dimension integer array where th
9. C Draws a line starting at X1 and Y1 and ending at X2 and Y2 LW is the line s width and is only valid for horizontal or vertical lines It defaults to 1 if not specified or if the line is a diagonal BOX X1 Y1 W H IW C FILL Draws a box starting at X1 and Y1 which is W pixels wide and H pixels high LW is the width of the sides of the box and can be zero It defaults to 1 RBOX X1 Yl W H R C FILL Draws a box with rounded corners starting at X1 and Y1 which is W pixels wide and H pixels high R is the radius of the corners of the box It defaults to 10 CIRCLE X Y R LW A C FILL Draws a circle with X and Y as the centre and a radius R LW is the width of the line used for the circumference and can be zero defaults to 1 A is the aspect ratio which is a floating point number and defaults to 1 For example an aspect of 0 5 will draw an oval where the width is half the height TEXT X Y STRING JUSTIFICATION FONT SCALE C BC Displays a string starting at X and Y JUSTIFICATION is one or two letters where the first letter is the horizontal justification around X and can be L C or R for LEFT CENTER RIGHT and the second letter is the vertical placement around Y and can be T M or B for TOP MIDDLE BOTTOM The default justification is left top FONT and SCALE are optional and default to that set by the FONT command C is the drawing colour and BC is the ba
10. The same as above but with two stop bits enabled OPEN COM1 9600 1024 S2 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 Reading and Writing Once a serial port has been opened you can use any command or function that uses a file number to write and read from the port Generally the PRINT command is the best method for transmitting data and the INPUT function is the most convenient way of getting data that has been received When using the INPUT Q function the number of characters specified will be the maximum number of characters returned but it could be less if there are less characters in the receive buffer In fact the INPUTSQ function will immediately return an empty string if there are no characters available in the receive buffer The LOC function is also handy it will return the number of characters waiting in the receive buffer ie the number characters that can be retrieved by the INPUT Q function The POPO function will return true if there are no characters waiting The LOF function will return the space in characters remaining in the transmit buffer When outputting to a serial port ie using PRINT n dat the command will pause if the output buffer is full and wait until there is sufficient space to place the new data in the buffer before returning If the receive buffer overflows with inco
11. 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 MicroBlocks on the Back Shed Forum Micromite User Manual Page 31 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 con
12. etc MM DEVICE A string representing the device or platform that MMBasic is running on Currently this variable will contain one of the following Maximite on the standard Maximite and compatibles Colour Maximite on the Colour Maximite and UBW32 DuinoMite when running on one of the DuinoMite family DOS when running on Windows in a DOS box Generic PIC32 for the generic version of MMBasic on a PIC32 Micromite on the PIC32MX150 250 Micromite MkII on the PIC32MX170 270 Micromite Plus on the PIC32MX470 MM HRES MM VRES The horizontal and vertical resolution of the LCD display panel if configured in pixels MM FONTHEIGHT MM FONTWIDTH The height and width of the current font in pixels 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 UC Following an DC 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 Micromite User Manual Page 49 Commande Note that the commands related to the TC 1 Wire and SPI communications functions are not listed here but are
13. use Octopart http octopart com to search for suppliers 28 pin Chips The best chip to use is the PIC32MX170F256B S0I 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 in a 28 pin package PIC32MX170F256B 50I SP Guaranteed to run at 483MHz 28 pin DIL package PIC32MX170F256B 50I SO_ As above but is in a surface mount SOIC package PIC32MX170F256B I SP Should run at 483MHz despite its 40MHz spec 28 pin DIL package PIC32MX170F256B I SO As above but is in a surface mount SOIC package 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 44 pin Chips 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
14. 3 3V maximum COM xxx These are used for serial communications see Appendix A PC xxx These are used for DC 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 User Manual Page 7 44 pin Micromite Connections The following diagram shows the possible functions of each I O pin on the 44 pin Micro
15. 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 Micromite User Manual Page 73 PEEK VAR var offset or PEEK VARTBL offset or PEEK PROGMEM offset 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 address while loword is the bottom 16 bits This command is for expert users only The PIC32 maps all control registers flash program memory and volatile RAM memory into a single address space so there is no need for INP or OUT commands The PIC32MX170 Family Data Sheet lists the details of this address space RAM starts at Ox AO000000 Program Flash starts at Ox9D000000 and Boot Flash starts at Ox9FCO0000 PI Returns the value of pi PIN pin Returns the value on the external I O pin Zero means digital low 1 means digital high and for analogue inputs i
16. GOSUB RTC GETTIME RTC GETTIME will get the current date time from a PCF8563 DS1307 or DS3231 or DS3232 real time clock and set the internal MMBasic clock RTC SETTIME year month day hour minute second or RTC SETREG reg value or RTC GETREG reg var or RTC PINS dat clk accordingly The date time can then be retrieved with the DATE and TIMES 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 Micromite User Manual Page 65 information in the chip s battery backed RAM These chips are UC devices and must be connected to the two UC pins with appropriate pullup resistors If the DC 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 RUN Run the program held in flash memory SELECT CASE va
17. 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 lt type gt 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 Micromite User Manual Page 43 As another example let us say that you need a function to format time in the AM PM format FUNCTION MyTimeS hours minutes LOCAL h h hours IF hours gt 12 THEN h h 12 MyTimeS STRS h STRS minutes IF hours lt 12 THEN MyTimeS MyTimeS AM ELSE MyTimeS MyTimeS 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 Arguments by Reference If you use an ordinary variable ie not an expression as the value when calling a subroutine or a function the argument within the subroutine function will point back to the variable used in the call and any changes to the argument w
18. Not configured or inactive 1 Analog input 2 Digital input 3 Frequency input 4 Period input 5 Counting input 8 Digital output 9 Open collector digital output In this mode SPINQ will also return the value on the output pin Following a command from the master that requests an input the master must then issue a second DC command to read 12 bytes The slave will respond by sending the value as a 12 character string This program can fall over if the master issues an incorrect command For example by trying to read from a pin that is not an input If that occurs an error will be generated and MMBasic will exit to the command prompt Rather than trap all the possible errors that the master can make this program uses the watchdog timer If an error does occur the watchdog timer will simply reboot the Micromite and the program will restart because AUTORUN is on and wait for the next message from the master The master can tell that something was wrong because it would get a timeout Micromite User Manual Page 85 This is the complete program running on the slave OPTION AUTORUN ON DIM msg 2 array used to hold the message I2C SLAVE OPEN amp H26 0 0 WriteD ReadD slave s address is 26 hex DO the program loops forever VATCHDOG 1000 this will recover from errors LOOP SUB ReadD received a message I2C SLAVE REA
19. This function will recognise the amp H prefix for a hexadecimal number amp O for octal and amp B for binary Micromite User Manual Page 76 Obsolete Commands and Functions These commands and functions are mostly included to assist in converting programs written for Microsoft BASIC For new programs the corresponding commands in MMBasic should be used IF condition THEN linenbr For Microsoft compatibility a GOTO is assumed if the THEN statement is followed by a number A label is invalid in this construct New programs should use IF condition THEN GOTO linenbr label IRETURN Returns from an interrupt when the interrupt destination was a line number or a label New programs should use a user defined subroutine as an interrupt destination In that case END SUB or EXIT sub will cause a return from the interrupt SPC number This function returns a string of blank spaces number bytes long It is similar to the SPACE function and is only included for Microsoft compatibility WHILE expression WEND WHILE initiates a WHILE WEND loop The loop ends with WEND and execution reiterates through the loop as long as the expression is true This construct is included for Microsoft compatibility New programs should use the DO WHILE LOOP construct Micromite User Manual Page 77 Appendix A Serial Communications Two serial ports are available for asynchronous serial commu
20. 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 OPTION LCDPANEL ILI9163 orientation D C pin reset pin LCS pin or OPTION LCDPANEL DISABLE Configures the Micromite and Micromite Plus to work with an attached LCD panel using the ILI9163 controller orientation can be LANDSCAPE PORTRAIT RLANDSCAPE or RPORTRAIT These can be abbreviated to L P RL or RP The R prefix indicates the reverse or upside down orientation C D pin and reset pn are the Micromite I O pins to be used for these functions Any free pin can be used CS pin can also be any I O pin but is optional If a touch controller is not used this parameter can be left off the command and the CS pin on the LCD display wired permanently to ground If the touch controller is used this pin must then be specified and connected to a Micromite I O pin NOTE The CPU speed must be 20MHz or greater OPTION LIST This will list the settings of any options that have been
21. 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 amp H26 0 3 1 pinnbr cfg IF MM 12C THEN ERROR Slave did not respond I2C CLOSE END SUB Micromite User Manual Page 86 set the output of an I O pin on the slave SUB SPIN pinnbr dat I2C OPEN 100 1000 I2C WRITE amp H26 0 3 2 pinnbr dat IF MM 12C THEN ERROR Slave did not respond I2C CLOSE END SUB get the input of an I O pin on the slave FUNCTION SPIN pinnbr LOCAL t I2C OPEN 100 1000 I2C WRITE amp H26 0 3 3 pinnbr 0 I2C READ amp H26 0 12 t IF MM I2C THEN ERROR Slave did not respond I2C CLOSE SPin VAL t END FUNCTION These use the new names for the DC functions so on the Maximite version 4 5 or later of MMBasic will be required Earlier versions of MMBasic on the Maximite will also work but the UC command names will have to be changed to the old standard Also the method of getting the string from the slave in SPIN pinnbr will have to be changed earlier versions did not support receiving data into a string variable Micromite Use
22. can be defined they will not be visible because a constant defined inside a subroutine is local to a subroutine However DIM will create variables that are global that that should be used instead Delayed Start Up 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 2 3 to 3 6V 50K 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 47uF capacitor and with the values shown will delay start up by about 350mS 47 uF The 1K resistor is there to ensure the safe discharge of the 47uF capacitor when the power is removed SC Micromite Micromite User Manual Page 17 Single Secure HEX File If you write a program for the Micromite and set the following options OPTION BREAK 0 OPTION AUTORUN ON you will end up with a program that cannot be stopped or interrupted To further bullet proof it you could use the watchdog timer and OPTION PIN You can then use a PICKit3 and MPLAB IPE to read the complete flash memory of the Micromite and export it as a hex file This will contain the Micromite firmware as well as your BASIC program and the above options This f
23. 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 e Arrays cannot be saved with this command e The storage space available to this command is 2KB e If when using RESTORE a variable with the same name already exists its value will be overwritten e Using VAR RESTORE without a previous save will have no effect and will not generate an error e 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 Micromite User Manual Page 69 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 t
24. chip It must be a high quality capacitor not an electrolytic and should have a minimum value of 10uF with an ESR Equivalent Series Resistance of less than 19 The recommended capacitor is a 47uF tantalum or a 10uF 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 VT 100 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 VT 100 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 User Manual Page 9 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 a couple of dollars 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 con
25. 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 SPINO 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 DC The following illustration shows the connections required for 28 pin chips 3 3V Micromite 2 Slave Micromite 1 Master Additional Input Outputs DC DATA Program Running On the Slave The slave must first set up its DC interface to respond to requests from the master With that done it can then drop into an infinite loop while the job of responding to the master is handled by the DC interrupts In the program below the slave will listen on DC address 26 hex for a three byte command from the master The format of this message is e Byte 1 is the command type It can have one of three values 1 means configure the pin 2 means set the output of the pin and 3 means read the input of the pin e Byte 2 is the pin number to operate on e Byte 3 is the configuration number if the command byte is 1 the output of the pin if the command byte is 2 or a dummy number if the command byte is 3 The configuration number used when configuring a slave s I O pin is the same as used in earlier versions of Maximite MMBasic with the SETPIN command and can be any one of 0
26. 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 Micromite User Manual Page 2 Contents VVEOCUUICU OAS se 2e eo ale EAEE ds tes e ele taal lente are ao Ge laden steal ate tives dares eretdie ule isiarerec tenders 4 Suitable Atertlinn e Sien Sentier e Sen 5 Programming the Firmware er ata s ate At a eee A os a a ah atte 6 28 pin Micromite Connections EE 7 44 pitrMicromite Connecting mpri r aa 8 Etat Ke ER 9 BE RE 12 Micromite Special Feat rgSiisiiirin rin a Eaa a aa Enr Enni 14 US ESI Ssh EE Ehe 19 BKS 10 63 nee ee 21 Using ie HE RE 22 Special Ree UE Re 25 F lkScreen E 33 Defining and Wsing Ee EE 35 OFT gfe hue 38 BI lee GE 41 Defined Subroutines and Funchons ee 42 Electrical Characteristics lt c n maui ec areca ct ie eee cis anche lees at ieee ea 46 E Ee Ne Ee 47 Predefined Read Only Variables AEN 49 en E le C Ae EE AETA A A 50 leren 71 Obsolete Commandsand nee 77 Appendix A Serial Communications EE 78 Appendix B 12C Communications un 82 Appendix C 1 Wire Communicatons ENEE 88 Appendix D SPI Rinnen EE 89 Micromite User Manual Page 3 Introduction The Micromite is a low cost Microchip PIC32 microcontroller programmed with the MMBasic firmware MMBasic is a Microsoft BASIC compatible implementation of the BASIC language with floating point integ
27. construct can be also replaced with GOTO linenumber label IF expression THEN lt statements gt ELSE lt statements gt ELSEIF expression THEN lt statements gt 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 Micromite User Manual Page 57 INPUT prompt string list of variables 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 INPU
28. described in the appendices at the end of this document Commands related to the SD card LCD displays touch input etc are covered in the Micromite Advanced Features manual 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 Shortcut for the PRINT command AUTOSAVE Enter automatic program entry mode This command will take lines of text from the console serial input and save them to memory This mode is terminated by entering Control Z which will then cause the received data to be saved into program memory overwriting the previous program At any time this command can be aborted by Control C which will leave program memory untouched This is one way of transferring a BASIC program into the Micromite The program to be transferred can be pasted into a terminal emulator and this command will capture the text stream and store it into program memory It can also be used for entering a small program directly at the console input BOX xl yl w h 1w Lc fill Draws a box starting at x1 and y1 which is w pixels wide and h pixels high on the attached LCD panel lw is the width of the sides of the box and can be zero It defaults to 1 c specifies the colour and defaults to the default foreground colour if not specified fill is the
29. error eg the sensor is not connected or communicating correctly the command will return 1000 for both the temperature and humidity For example HUMID 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 Real Time Clock Interface Using the RTC GETTIME command it is easy to get the current time from a PCF8563 DS1307 DS3231 or DS3232 real time clock as well as compatible devices such as the M41T11 These integrated circuits are popular and cheap will keep accurate time even with the power removed and can be purchased for 2 to 8 on eBay Complete modules including the battery can also be purchased on eBay for a little more The PCF8563 and DS1307 will keep time to within a minute or two over a 3 3V month while the DS3231 and DS3232 are particularly precise and will remain accurate to within a minute over a year Lithium 3V button cell These chips are UC devices and should pa be connected to the UC I O pins of the Micromite This circuit shows a typical circuit for the DS1307 The other chips have similar circuits check their data sheets 32 768 crystal Internal pullup resistors LOOK are applied to the I C I O pins so in many cases external resistors as shown in the diagram would not be needed Before you can use the chip its time
30. fill colour It can be omitted or set to 1 in which case the box will not be filled See the section Basic Drawing Commands for a definition of the colours and graphics coordinates CIRCLE x y r lw a c fill Draw a circle on the video output centred at x and y with a radius of r on the attached LCD panel c is the optional colour and defaults to the current foreground colour if not specified The optional a is a floating point number which will define the aspect ratio If the aspect is not specified the default is 1 0 which gives a standard circle fill is the fill colour It can be omitted or set to 1 in which case the box will not be filled See the section Basic Drawing Commands for a definition of the colours and graphics coordinates CLS colour Clears the LCD panel s screen Optionally colour can be specified which will be used for the background when clearing the screen COLOUR fore back Sets the default colour for commands PRINT etc that display on the on the or attached LCD panel Tore is the foreground colour back is the background COLOR fore back colour The background is optional and if not specified will default to black CSUB name Defines the binary code for an embedded machine code program module hex hex hex hex END CSUB written in C or MIPS assembler The module will appear in MMBasic as the command or function name and ca
31. integer division operator Functions will return a float or integer depending on their characteristics For example PINQ will return an integer when the pin is configured as a digital input but a float when configured as an analog input If necessary you can convert a float to an integer with the INTQ function It is not necessary to specifically convert an integer to a float but if it was needed the integer value could be assigned to a floating point variable and it will be automatically converted in the assignment 64 bit Unsigned Integers The Micromite supports 64 bit signed integers This means that there are 63 bits for holding the number and one bit the most significant bit which is used to indicate the sign positive or negative However it is possible to use full 64 bit unsigned numbers as long as you do not do any arithmetic on the numbers 64 bit unsigned numbers can be created using the amp H amp O or amp B prefixes to a number and these numbers can be stored in an integer variable You then have a limited range of operations that you can perform on these numbers They are lt lt shift left gt gt shift right AND bitwise and OR bitwise or XOR bitwise exclusive or equal to and lt gt not equal to Arithmetic operators such as etc will be confused by a 64 bit unsigned number and will return nonsense results To display 64 bit unsigned numbers you should use the HEX OCT Q or BIN Q functions
32. 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 lt statements gt 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 gt 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
33. number of characters that must be waiting in the receive queue before the receive interrupt subroutine is called The default is 1 character All parameters except the serial port name COMn are optional If any one parameter is left out then all the following parameters must also be left out and the defaults will be used Five options can be added to the end of comspec These are DE 9BIT INV OC and S2 e DE will enable the Data output Enable EN signal for RS485 See the section IEEE 485 for details e OBIT will specify that 9 bit transmit and receive is to be used See the section IEEE 485 for details e INV specifies that the transmit and receive polarity is inverted COM1 only e OC will force the transmit pin and DE on COM1 to be open collector This option can be used on both COM1 and COM2 The default is normal 0 to 3 3V output e S2 specifies that two stop bits will be sent following each character transmitted COM1 only Input Output Pin Allocation When a serial port is opened the pins used by the port will be automatically set to input or output as required and the SETPIN and PIN commands will be disabled for the pins When the port is closed using the CLOSE command all pins used by the serial port will be set to a not configured state and the SETPIN command can then be used to reconfigure them The connections for each COM port are shown in the pinout diagrams in the beginning of this manu
34. protected from being listed or modified by a PIN number Nineteen input output pins are available on the 28 pin chip and 33 on the 44 pin chip These can be independently configured as digital input or output analog input frequency or period measurement and counting Within MMBasic the I O pins can be dynamically configured as inputs or outputs with or without pullups or pulldowns MMBasic commands will generate pulses and can be used to transfer data in parallel Interrupts can be used to notify when an input pin has changed state 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 TFT LCD display panels using the ILI9341 and other controllers are supported allowing the BASIC program to display text and draw lines circles boxes etc in 16 383 colours Resistive touch controllers on these panels are also supported allowing them to be used as sophisticated input devices These LCD panels typically cost US 7 and provide a low cost high tech graphical user interface 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
35. retrieve the temperature reading The TEMPRQ function will always wait if the sensor is still making the measurement Micromite User Manual Page 26 For example TEMPR START 15 lt do other tasks gt PRINT Temperature TEMPR 15 Measuring Humidity and Temperature The HUMID command will read the humidity and temperature from a DHT22 humidity temperature sensor This device is also sold as the RHT03 or AM2302 but all are compatible and can be purchased on eBay for under 5 The DHT22 can be powered from 3 3V or 5V SV is 3V to Sao recommended and it should have a pullup resistor on 5V die Vi S the data line as shown This is suitable for long cable 47K Kr runs up to 20 meters but for short runs the resistor can be omitted as the Micromite also provides an internal Any G weak pullup Micromite To get the temperature or humidity you use the HUMID V O Pin command with three arguments as follows HUMID pin tVar hVar 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
36. same number as a built in font and in that case it will replace the built in font Each hex must be exactly eight hex digits and be separated by spaces or new lines from the next e Multiple lines of hex words can be used with the command terminated by a matching END DEFINEFONT e Multiple embedded fonts can be used in a program with each defining a different font with a different font number e During execution MMBasic will skip over any DEFINEFONT commands so they can be placed anywhere in the program e Any errors in the data format will be reported when the program is saved DIM type decl decl where decl is var length type init var is a variable name with optional dimensions length is used to set the maximum size of the string to n as in LENGTH n type is one of AS FLOAT or AS INTEGER or AS STRING init is the value to initialise the variable and consists of lt expression gt For a simple variable one expression is used for an array a list of comma separated 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 Declares one or more variables ie makes the variable name and its characteristics known to the inter
37. should have external pullup resistors installed typical values are 1OKQ for 100KHz or 2KQ for 400 kHz Weak pullups about 100K on both the clock and data lines can also be specified in the I2C OPEN command I2C normally requires lower value resistors but for short signal lines at slow speeds this may be all that is required When the UC 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 I C 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 DC 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 IC 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 Micromite User Manual Page 84 This example converts a Micromite into a general purpose I O expansion
38. 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 Microsoft s GW BASIC There are numerous differences due to physical and practical considerations but most standard BASIC 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 SELECT CASE statements and structured IF THEN ELSE ENDIF statements Micromite User Manual Page 48 Predefined Read Only Variables These variables are set by MMBasic and cannot be changed by the running program MM VER 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
39. that Note that the modulation frequency used is 38KHz and this matches the common IR receivers described in the previous page for maximum sensitivity when communicating between two Micromites Measuring Temperature The TEMPR 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 T O pin and pullup resistor is required for each one ay 5V To get the current temperature you just use the TEMPRO function in an expression For example Any PRINT Temperature TEMPR pin ee In 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 25 C 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 TEMPR START command then later use the TEMPR function to
40. the Micromite This only requires a VT 100 terminal emulator and can edit the whole program in one session It includes advanced features such as colour codes syntax search and copy cut and paste to and from a clipboard Programs can be easily transferred from another computer Windows Mac or Linux using the XModem protocol or by streaming the program over the serial console input A comprehensive range of communications protocols are implemented including TC asynchronous serial RS232 IEEE 485 SPI and 1 Wire These can be used to communicate with many sensors temperature humidity acceleration etc as well as for sending data to test equipment The Micromite has built in commands to directly interface with infrared remote controls the DS18B20 temperature sensor LCD display modules battery backed clock numeric keypads and more Special embedded controller features in MMBasic allow the CPU to be put to sleep or the clock speed to be varied to balance power consumption and speed 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 Power requirements are 2 3 to 3 6 volts at 6 to 31mA Micromite User Manual Page 4 Suitable Microcontrollers The standard Micromite firmware will run on the following PIC32 microcontroller manufactured by Microchip These are available from Microchip http www microchipdirect com or their distributors
41. the input cycles It can be any number between 10mS and 100000mS Note that the PINO 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 PINO 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 collector or more correctly open drain The function PINQ can also be used to return the value on the output pin Previous versions of MMBasic used numbers for cfg and the mode OOUT For backwards compatibility they will still be recognised See the function PIN for reading inputs and the statement PINQ for setting an output See the command below if an interrupt is configured SETPIN pin cfg target option Will configure pin to generate an interrupt according to cfg Any I O pin capable of digital input can be configured to generate an interrupt with a maximum of ten interrupts configured at any one time cfg is a keyword and can be any one of the following OFF Not configured or
42. the maximum is 18 9mS Most servos will accept a range of Micromite User Manual Page 66 0 8mS to 2 2mS The output will run continuously in the background while the program is running and can be stopped using the STOP command The pulse widths of the outputs can be changed at any time without stoping the output by issuing a new SERVO command The SERVO function will take control of any specified outputs and when stopped the pins will be returned to a high impedance not configured state See the section Special Hardware Devices for more details SETPIN pin cfg option 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
43. this mode the status line will change to show the functions of the function keys in the mark mode These keys are ESC Will exit mark mode without changing anything F4 CUT Will copy the marked text to the clipboard and remove it from the program F5 COPY Will just copy the marked text to the clipboard DELETE Will delete the marked text leaving the clipboard unchanged You can also use control keys instead of the functions keys listed above These control keystrokes are LEFT Ctrl S RIGHT Ctrl D UP Ctrl E DOWN Ctrl X HOME Ctrl U END Ctrl K PageUp Ctrl P PageDn Ctrl L DEL Ctrl INSERT Ctrl N F1 Ctrl Q F2 Ctrl W F3 Ctrl R ShiftF3 Ctrl G F4 Ctrl T F5 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 wor
44. variable s type after the variable with the keyword AS For example DIM nbr AS INTEGER str AS STRING In this case the type of each variable is set individually not as a group as when the type is placed before the list of variables The variables can also be initialised while being defined For example DIM INTEGER a 5 b 4 c 3 DIM s World i amp FHHHHHHH DIM str AS STRING Hello si Note that the value used to initialise the variable can be an expression including user defined functions The DIM or LOCAL commands are also used to define an array and all the rules listed above apply when defining an array For example you can use DIM INTEGER nbr 10 nbr2 nbr3 5 8 etc When initialising an array the values are listed as comma separated values with the whole list surrounded by brackets For example DIM INTEGER nbr 5 12 13 14 15 16 or iw IM days 7 AS STRING Sun Mon Tue Wed Thu Fri Sat Micromite User Manual Page 36 CONST Often it is useful to define an identifier that represents a value without the risk 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 th
45. which will cause a white dot to be placed on the display marking the touch position on the screen HUMID pin tvar hvar Returns the temperature and humidity using the DHT22 sensor Alternative versions of the DHT22 are the AM2303 or the RHTO3 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 HUMID 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 1OMHz 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 IF expr THEN statement or IF expr THEN stmt ELSE stmt 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
46. 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 Guaranteed to run at 48MHz PIC32MX170F256DI PT Should run at 483MHz despite its 4OMHz spec These chips are in a TQFP surface mount package with 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 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 PICMX150 Series Chips The first versions of the Micromite firmware ran on the PIC32MX150F128 series of chips The firmware described in this manual will only run on the newer PIC32 chips listed above however the firmware for the original Micromite running on the MX150 series of chips is still available It can be found in the download section of http geoffg net micromite html and is supplied with its own manual Micromite User Manual Page 5 Programming the Firmware 28 pin Chips To program the Micromite firmware into the microcontroller you need a suitable progr
47. which will trim specified characters from the start and end of a string The following provides an example of how to construct such a simple function in MMBasic The first argument to the function is the string to be trimmed and the second is a string containing the characters to trim from the first string RTrim will trim the specified characters from the end of the string LTrim Q from the beginning and Trim from both ends trim any characters in c from the start and end of s Function Trim s c Trim S RTrimS LTrim s c c End Function trim any characters in c from the end of s Function RTrim s cS RTrim s Do While Instr c Right RTrimS 1 RTrim Mid RTrimS 1 Len RTrimS 1 Loop End Function trim any characters in c from the start of s Function LTrim s cS LTrim S Do While Instr cS Left LTrims 1 LTrimS Mid LTrim S 2 Loop End Function As an example of using these functions S BARA SOO LOO T PRINT Trim s Will give 23 56700 PRINT Trim s 0 Will give 23 567 PRINT LTrim ss 0 Will give 23 56700 Micromite User Manual Page 45 Electrical Characteristics Power Supply Voltage range Current draw Current in sleep Digital Inputs Logic Low Logic High Input Impedance Frequency Response Analog Inputs Voltage Range Accuracy Input Impedance Digital Outputs 2 3 to 3 6V 3 3V nom
48. zero as the leading padding character s CHR number Returns a one character string consisting of the character corresponding to the ASCII code indicated by argument number CINT number Round numbers with fractional portions up or down to the next whole number or integer For example 45 47 will round to 45 45 57 will round to 46 34 45 will round to 34 34 55 will round to 35 See also INT and FIX COS number Returns the cosine of the argument number in radians DATE Returns the current date based on MMBasic s 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 DATES DEG radians Converts radians to degrees DISTANCE trigger echo or DISTANCE trig echo Measure the distance to a target using the HC SR04 ultrasonic distance sensor Four pin sensors have separate trigger and echo connections trigger is the I O pin connected to the trig input of the sensor and echo is the pin connected to the echo output of the sensor Three pin sensors have a combined trigger and echo connection and in that case you only need to specify one I O pin to interface to the sensor Note that any I O pins used with the HC SR04 should be 5V capable as the HC SR04 is a 5V device The I O pins are automatically configured by t
49. 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 9 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 9 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 9 bit should be set or 0 for not set This 9 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 4800 9BIT as 1 PRINT 1 CHRS 211 PRINT 0O CHRS 23 PRINT O CHRS 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 cha
50. ALIBRATE Finally you can enter and run the program OPTION EXPLICIT CONST DBlue RGB O 0 128 A dark blue colour COLOUR RGB GREEN RGB BLACK FONT 1 3 BOX 0 0 MM HRes 1 MM VRes 2 3 RGB RED DBlue DO TEXT MM HRes 2 MM VRes 4 TIMES CM 1 4 RGB CYAN DBlue TEXT MM HRes 2 MM VRes 3 4 DATES CM IF TOUCH X lt gt 1 THEN END LOOP The program starts by defining a constant with a value corresponding to a dark blue colour and then sets the defaults for the colours and the font It then draws a box with red walls and a dark blue interior Following this the program enters a continuous loop where it performs three functions 1 Displays the current time inside the previously drawn box The string is drawn centred both horizontally and vertically in the middle of the box Note that the TEXT command overrides both the default font and colours to set its own parameters 2 Draws the date centred in the lower half of the screen In this case the TEXT command uses the default font and colours previously set 3 Checks for a touch on the screen This is indicated when the TOUCH X function returns something other than 1 In that case the program will terminate The screen display should look like this the font used in this illustration is different Micromite User Manual Page 24 Special Hardware Devices To make it e
51. D 3 msg recvd get the message into the array IF msg 0 1 THEN command 1 SETPIN msg 1 msg 2 configure the I O pin ELSEIF msg 0 2 THEN command 2 PIN msg 1 msg 2 set the I O pin s output ELSE the command must be 3 s strS pin msg 1 Space 12 get the input on the I O pin ENDIF END SUB return from the interrupt SUB WriteD request from the master I2C SLAVE WRITE 12 s send the last measurement END SUB return from the interrupt Interface Routines On the Master These routines can be run on another Micromite or a Maximite or some other computer with an I C interface They assume that the slave Micromite is listening on DC address 26 hex If necessary these can be modified to access multiple Micromites with different addresses all acting as expansion chips and providing an almost unlimited expansion capability There are two subroutines and one function that together are used to control the slave SSETPIN pin cfg SPIN pin output nn SPIN pin This subroutine will setup an I O pin on the slave It operates the same as the MMBasic SETPIN command and the possible values for cfg are listed above This subroutine will set the output of the slave s pin to output ie high or low 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 PRINT SPI 1 N 3 As
52. ETE will remove the library and recover the memory used LIBRARY LIST will list the contents of the library Note that any code in the library that is not contained within a subroutine or function will be executed immediately before a program is run This can be used to initialise constants set options etc LINE INPUT prompt string variable Reads an entire line from the console input into string variable If specified the prompt will be printed first Unlike INPUT this command will read a whole line not stopping for comma delimited data items A question mark is not printed unless it is part of prompt LINE INPUT nbr string variable Same as above except that the input is read from a serial communications port previously opened for INPUT as nbr See the OPEN command Micromite User Manual Page 59 LIST or LIST ALL List a program on the serial console LIST on its own will list the program with a pause at every screen full LIST ALL will list the program without pauses This is useful if you wish to transfer the program in the Micromite to a terminal emulator on a PC that has the ability to capture its input stream to a file LOCAL variable variables See DIM for the full syntax Defines a list of variable names as local to the subroutine or function This command works exactly the same as DIM except that the variables will only be visible within the subrout
53. Eg a scale of 2 will double the height and width FOR counter start TO finish Initiates a FOR NEXT loop with the counter initially set to start and STEP increment 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 FUNCTION xxx arg1 Defines a callable function This is the same as adding a new function to arg2 AS lt type gt MMBasic while it is running your program lt statements gt xxx is the function name and it must meet the specifications for naming a lt statements gt i variable The type of the function can be specified by using a type suffix XXX lt return value gt ie xxx or by specifying the type using AS lt type gt at the end of the END FUNCTION ee i functions definition For example FUNCTION xxx argl arg2 AS STRING org arg2 etc are the arguments or parameters to the function An array is specified by using empty brackets ie arg3 The type of the argument can be specified by using a type suffix ie arg1 or by specifying the type using AS lt type gt ie argl AS STRING 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
54. HEN FLASH If the FLASH subroutine was in program memory you could even try it out at the command prompt just like any command in MMBasic The definition of the FLASH subroutine can be anywhere in the program but typically it is at the start or end If MMBasic runs into the definition while running your program it will simply skip over it Subroutine Arguments Defined subroutines can have arguments sometimes called parameter lists In the definition of the subroutine they look like this SUB MYSUB argl arg2 arg3 lt statements gt lt statements gt END SUB And when you call the subroutine you can assign values to the arguments For example YSUB 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 arg2S 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 b
55. ION 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 ERASE variable variable Deletes arrayed variables and frees up the memory Use CLEAR to delete all variables including all arrayed variables ERROR error_msg Forces an error and terminates the program This is normally used in debugging or to trap events that should not occur EXIT DO EXIT FOR EXIT FUNCTION EXIT SUB EXIT DO provides an early exit from a DO LOOP EXIT FOR provides an early exit from a FOR NEXT loop EXIT FUNCTION provides an early exit from a defined function EXIT SUB provides an early exit from a defined subroutine The old standard of EXIT on its own exit a do loop is also supported Micromite User Manual Page 55 FONT font number scaling This will set the default font for displaying text on an LCD panel Fonts are specified as a number For example 2 the is optional See the section Basic Drawing Commands for details of the available fonts scaling can range from 1 to 15 and will multiply the size of the pixels making the displayed character correspondingly wider and higher
56. Micromite User Manual MMBasic Ver 5 0 For updates to this manual and more details on MMBasic go to http qeoffg net micromite html and _http mmbasic com Copyright The Micromite firmware including MMBasic and this manual are Copyright 2011 2015 by Geoff Graham USB CDC and SD FAT Support is Copyright 2010 2011 Microchip Technology Incorporated DC Support is Copyright 2011 Gerard Sexton 1 Wire Support is Copyright 1999 2006 Dallas Semiconductor Corporation and 2012 Gerard Sexton The USB VID and PIDs are sublicensed by Microchip Technology Incorporated for this project Acknowledgement and thanks to Phil Boyce WhiteWizard for supporting the Micromite s development with much needed hardware Peter Mather matherp for introducing low cost LCD panels and the ILI9341 and ST7735S drivers and Peter Carnegie G8JCF for his help in developing the CFunction functionality Also thanks to the more than 50 members of the Back Shed forum who have beta tested the Micromite firmware over the past two years The compiled object code the hex file for the standard Micromite 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
57. NTINUE Resume running a program that has been stopped by an END statement an error or CTRL C The program will restart with the next statement following the previous stopping point CONTINUE DO Skip to the end of a DO LOOP or a FOR NEXT loop The loop condition or will then be tested and if still valid the loop will continue with the next CONTINUE FOR iteration CPU speed Set the clock speed of the processor speed is set in MHz and can be either 48 40 30 20 10 or 5 Current drawn by the chip is proportional to the clock speed so by halving the clock speed the current drain is roughly halved The default speed of the CPU when power is applied is 40MHz When the speed is changed all timing functions in MMBasic will be automatically corrected to keep the correct time and the console baud rate Micromite User Manual Page 51 will be unchanged The serial communications ports can remain open during the speed change and their speed will be adjusted accordingly Note that there may be a glitch while changing speed and some characters may be lost or corrupted The speed of any SPI DC and PWM functions open at the time will change with the clock speed For this reason they should be closed before this command is used and reopened after CPU SLEEP seconds or CPU SLEEP 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 sec
58. Speed 00000000 3c02bf81 8c45f000 8c43f 000 3c02003d 24420900 7ca51400 70a23002 3c040393 34848700 7c6316c0 00c41021 00621007 3c03029f 24636300 10430005 00402021 00002821 00801021 03e00008 00a01821 3c0402dc 34846c00 00002821 00801021 03e00008 00a01821 End CFunction This would have the effect of adding a new function called CPUSpeed to MMBasic You could even run it at the command prompt gt PRINT CPUSpeed 40000000 gt Micromite User Manual Page 16 Program Initialisation The library can also include code that is not contained within a subroutine function or CFunction This code if it exists will be run automatically before a program starts running ie via the RUN command This feature can be used to initialise constants or setup MMBasic in some way For example if you wanted to set some constants you could include the following lines in the library code CONST TRUE 1 CONST FALSE 0 For all intent and purposes the identifiers TRUE and FALSE have been added to the language and will be available to any program that is run on the Micromite MM STARTUP There may be a need to execute some code on initial power up regardless of the program in main memory Perhaps to initialise some hardware set some options or print a custom startup banner This can be accomplished by creating a subroutine with the name MM STARTUP and saving it in the library space see above When the Micromite is first powered
59. T as nbr See the OPEN command IR dev key int or IR CLOSE Decodes NEC or Sony infrared remote control signals An IR Receiver Module is used to sense the IR light and demodulate the signal It should be connected to the IR pin see the pinout tables This command will automatically set that pin to an input The IR signal decode is done in the background and the program will continue after this command without interruption dev and key should be numeric variables and their values will be updated whenever a new signal is received dev is the device code transmitted by the remote and key is the key pressed int is a user defined subroutine that will be called when a new key press is received or when the existing key is held down for auto repeat In the interrupt subroutine the program can examine the variables dev and key and take appropriate action The IR CLOSE command will terminate the IR decoder and return the I O pin to a not configured state See the section Special Hardware Devices for more details IR SEND pin dev key Generate a 12 bit Sony Remote Control protocol infrared signal pin is the I O pin to use This can be any I O pin which will be automati cally configured as an output and should be connected to an infrared LED Idle is low with high levels indicating when the LED should be turned on dev is the device being controlled and is a number from 0 to 31 key is the
60. a period of say 100 seconds you should be prepared to wait that amount of time before the PINQ 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 DC 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
61. al Note that Tx means an output from the Micromite and Rx means an input to the Micromite The enable pin the EN signal for RS485 is an output The signal polarity is standard for devices running at TTL voltages for RS232 voltages see below Idle is voltage high the start bit is voltage low data uses a high voltage for logic 1 and the stop bit is voltage high These signal levels allow you to directly connect to devices like GPS modules which generally use TTL voltage levels Baud Rate On the 28 and 44 pin Micromites 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 Micromite User Manual Page 78 CPU Speed COM1 Maximum COM2 Maximum 48 MHz 282000 19200 40 MHz default 230400 19200 30 MHz 115200 9600 20 MHz 115200 9600 10 MHz 57600 4800 5 MHz 38400 2400 Note that below these limits any baud rate can be chosen for example 1111 bps is a valid speed for both ports 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 1 KB OPEN COM1 9600 1024 AS 8
62. ammer Probably the best is the Microchip PICKit 3 which is reasonably cheap at US 45 and clones can be purchased on the Internet for less than 20 If you install Microchip s MPLAB X free from Microchip it will also install MPLAB IPE which you can use with the PICKit 3 to program the chip See geoffg net programming_pics html for details These are the connections required for programming the 28 pin chip 2 3 to 3 6V 26mA PICKit 3 Connector MCLR Vcc GND PGD PGC NC On nm E A4 k 44 pin Chips 47uF 6V Ceramic or Tantalum Programming these is similar to programming the 28 pin version Refer to the following table for the pin connections on the microcontroller PICKit 3 Description 44 pin chip 47uF Tantalum Capacitor to GND 7 1 MCLR Master Reset active low 18 2 Vec Power Supply 3 3V 17 28 and 40 3 GND Ground 6 16 29 and 39 4 PGD Programming Data 21 5 PGC Programming Clock 22 6 NC Not used Notes e A pullup resistor of 10K is required between the MCLR pin and Vcc e The microcontroller being programmed can be powered by the PICKit 3 but it is recommended that a separate power supply be used When the PICKit 3 supplies the power pin 2 Vcc on the PICKit 3 will become an output supplying the power to the chip being programmed Micromite User Manual Page 6 28 pin Micromite Connections The following diagram shows the possible functi
63. ange from 10 to 50 To setup the display you use the LCD INIT command LCD INIT d4 db 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 DO 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 Micromite User Manual Page 28 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 3 3V V Vdd CONTRAST LCD Module Micromite D5 D4 D3 D2 Di DO GND RW To display characters on the module you use the LCD command LCD line pos data Where line is the line on the display 1 to 4 and pos is the position on the line where the data is to be written the first position on the line is 1 data is a string containing the data to write to the LCD display The characters in data will overwrite whatever was on that part of the LCD The following shows a typical usage where d4 to d7 are connected to pins 2 to 4 on the Micromite rs is connected to pin 23 and en to pin 24 LCD INIT 2 3 4 Op 23y 24 LCD 1 2 Temperature LCD 2 6 STRS TEMPR 15 DS18B20 connected to pin 15 Note that this example also uses the TEMPR fu
64. argument the C routine will receive a pointer to the memory allocated to the variable or array and the C routine can change this memory to return a value to the caller e 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 refer to the Embedded C Modules documentation in the Micromite firmware file CLEAR Delete all variables and recover the memory used by them See ERASE for deleting specific array variables CLOSE nbr nbr 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 Create a constant identifier which cannot be changed once created d is the identifier which follows the same rules as for variables The identifier can have a type suffix or but it is not required If it is specified it must match the type of expression expression is the value of the identifier and it can be a normal expression including user defined functions which will be evaluated when the constant is created A constant defined outside a sub or function is global and can be seen throughout the program A constant defined inside a sub or function is local to that routine and will hide a global constant with the same name CO
65. asier for a program to interact with the external world the Micromite includes drivers for a number of common peripheral devices These are e Infrared remote control receiver and transmitter e The DS18B20 temperature sensor and DHT22 temperature humidity sensor e LCD display modules e Numeric keypads e Battery backed clock e Servos e Ultrasonic distance sensor Infrared Remote Control Decoder You can easily add a remote control to your project using the IR command When enabled this function will run in the background and interrupt the running program whenever a key is pressed on the IR remote control It will work with any NEC or Sony compatible remote control including ones that generate extended messages Most cheap programmable remote controls will generate either protocol and using one of these you can add a sophisticated flair to your Micromite based project The NEC 3 3V protocol is also used by many other manufacturers including Apple Pioneer Sanyo Akai and Toshiba so their name brand remotes can be used To detect the IR signal you need an IR receiver connected to the IR pin pin 16 on a 28 pin chip as illustrated in the diagram The IR receiver will sense the IR light demodulate the signal and present it as a TTL voltage level signal to this pin Setup of the I O pin is automatically done by the IR command IR Receiver Micromite NEC remotes use a 38KHz frequency and suitable receivers tuned to that frequ
66. asures the width of an input pulse from 1S to 1 second with 0 1uS resolution pin is the I O pin to use for the measurement it must be previously configured as a digital input polarity is the type of pulse to measure if zero the function will return the width of the next negative pulse if non zero it will measure the next positive pulse UU is the timeout applied while waiting for the pulse to arrive t2 is the timeout used while measuring the pulse Both are in microseconds uS and are optional If t2 is omitted the value of t1 will be used for both timeouts If both t1 and t2 are omitted then the timeouts will be set at 100000 ie Micromite User Manual Page 74 100mS This function returns the width of the pulse in microseconds uS or 1 if a timeout has occurred With a CPU speed of 40MHz the measurement is accurate to 0 5 and 0 5uS At other speeds the measurement is slightly less accurate Note that this function will cause the running program to pause while the measurement is made and interrupts will be ignored during this period RAD degrees Converts degrees to radians RIGHTS string number of chars Returns a substring of string with number of chars from the right end of the string RND number Returns a pseudo random number in the range of 0 to 0 999999 The number value is ignored if supplied The RANDOMIZE command
67. at 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 F PIN InputVoltagePin gt 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 Mixing Floating Point and Integers MMBasic automatically handles conversion of numbers between floating point and integers If an operation mixes both floating point and integers eg PRINT A B the integer will be converted to a floating point number first then the operation performed and a floating point number returned If both sides of the operator are integers then an integer operation will be performed and an integer returned The one exception is the normal division which will always convert both sides of the expression to a floating point number and then return a floating point number For integer division you should use the
68. called a pullup or pulldown resistor and is handy when connecting to a switch as it saves having to install an external resistor to place a voltage across the contacts 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 PINO function will return the voltage For example gt SETPIN 23 AIN gt PRINT PIN 23 2 345 gt 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 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 Pow
69. 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 20 Each number specifies the number of elements in each dimension Normally the numbering of each dimension starts at 0 but the OPTION BASE DIM array 10 Micromite User Manual Page 53 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 stri
70. 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 Nor 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 Tot al would be wrong Nbr 1234 Incr 2 Total Nr Incr Micromite User Manual Page 35 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 gt LIST OPTION EXPLICIT DIM Nbr Incr Total Nbr 1234 Incr 2 Total Nr Incr gt gt RUN 5 Total Nr Incr Error Variable not declared gt The use of OPTION EXPLICIT is recommended to support go
71. changed from their default setting and are the type that is saved in flash This command is useful when configuring options that reserve I O pins ie OPTION LCDPANEL or OPTION TOUCH and you need to know what pins are in use Micromite User Manual Page 62 OPTION PIN nbr 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 RESET Reset all saved options including the PIN to the default values OPTION TAB 21418 Set the spacing for the tab key Default is 2 This option will be remembered even when the power is removed OPTION TOUCH T_CS pin T_IRQ pin Configures MMBasic for the touch sensitive feature of an attached LCD panel T_CS pin and T_IRQ pin are the Mic
72. ches program execution to the target which can be a line number or a label Micromite User Manual Page 56 GUI BITMAP x y bits width height scale c be Displays the bits in a bitmap on an LCD panel starting at x and vi on an attached LCD panel height and width are the dimensions of the bitmap as displayed on the LCD panel and default to 8x8 scale is optional and defaults to that set by the FONT command c is the drawing colour and bc is the background colour They are optional and default to the current foreground and background colours The bitmap can be an integer or a string variable or constant and is drawn using the first byte as the first bits of the top line bit 7 first then bit 6 etc followed by the next byte etc When the top line has been filled the next line of the displayed bitmap will start with the next bit in the integer or string See the section Basic Drawing Commands for a definition of the colours and graphics coordinates GUI CALIBRATE This command is used to calibrate the touch feature on an LCD panel It will display a series of targets on the screen and wait for each one to be precisely touched GUI TEST LCDPANEL Will test the display or touch feature or With GUI TEST LCDPANEL an animated display of colour circles will be GUI TEST TOUCH drawn rapidly drawn on top of each other With GUI TEST TOUCH the screen will blank and wait for a touch
73. ckground colour They are optional and default to that set by the COLOUR command GUI BITMAP X Y BITS WIDTH HEIGHT SCALE C BC Displays the bits in a bitmap starting at X and Y HEIGHT and WIDTH are the dimensions of the bitmap as displayed on the LCD panel and default to 8x8 SCALE C and BC are the same as for the TEXT command Micromite User Manual Page 23 The bitmap can be an integer or a string variable or constant and is drawn using the first byte as the first bits of the top line bit 7 first then bit 6 etc followed by the next byte etc When the top line has been filled the next line of the displayed bitmap will start with the next bit in the integer or string Example As an example the following program will draw a simple digital clock on an ILI9341 based LCD display The program will terminate and return to the command prompt if the display screen is touched First the display and touch options must be configured by entering commands similar to these at the command prompt OPTION LCDPANEL ILI9341 L 2 23 6 OPTION TOUCH 7 15 These specify an ILI9341 based display in the landscape orientation and uses pins 2 23 and 6 for the LCD and pins 7 and 15 for the touch controller all on the 28 pin Micromite Your configuration could be different Next the touch feature should be calibrated by entering this command and following the calibration procedure GUI C
74. configured state See the section Special Hardware Devices for more details LCD CMD d1 d2 etc or LCD DATA d1 d2 etc 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 LIBRARY SAVE or LIBRARY DELETE or LIBRARY LIST The library is a special segment of program memory that can contain program code such as subroutines functions and CFunctions These routines are not visible to the programmer but are available to any program running on the Micromite and act the same as built in commands and functions in MMBasic See the section The LIBRARY feature towards the start of this manual for a full explanation LIBRARY SAVE will take whatever is in normal program memory compress it remove redundant data such as comments and transfer it to the library area main program memory is then empty The code in the library will not show in LIST or EDIT and will not be deleted when a new program is loaded or NEW is used LIBRARY DEL
75. ctedly 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 Line Numbers Program Structure and Editing The structure of a program line is line number label command arguments command arguments A label or line number can be used to mark a line of code A label has the same specifications length character set etc as a variable name but it cannot be the same as acommand 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 paus
76. 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 Micromite User Manual Page 14 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 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 connect
77. e received data items will be saved This command sends zeros while reading the data from the slave SPI Close If required the SPI or SPI2 communications channel can be closed as follows the I O pins will be set to inactive SPI CLOSE Additional SPI Ports Additional SPI ports can be added to the Micromite by using the SPIPort embedded C module This is included in the Embedded C Modules folder in the Micromite firmware zip file Using the SPI with the Colour LCD and Touch Features The Micromites has only one standard SPI channel so this must be shared between the display and touch controllers if these features are used and the BASIC program To do this the SPI port must be opened in BASIC and closed again without any intervening commands that might cause MMBasic to send receive data to the display or touch controllers This includes commands such as CLS LINE etc and the TOUCH function The following provides an example The SPI port is opened and closed within the one function with no intervening graphic or touch commands PIN 26 1 preset the pin high before it is setup SETPIN 26 DOUT pin 26 will be used as the enable signal CIRCLE 100 100 50 draw a circle uses the SPI port nor ReadSPI get the SPI data x TOUCH X get the X touch location uses the SPI port nobr2 ReadSPI get the SPI data for a second time y TOUCH Y get the Y touch location uses the SPI port END
78. e touch controller the 16 pin IC on the bottom right of the PCB but there is not much point in purchasing these as the price difference is small Be aware that some eBay sellers show a photo of the board with the touch controller but further down the listing state that their product does not support touch Connecting SPI Based LCD Panels The SPI based display controllers share the Micromite s SPI interface with the touch controller if present and the BASIC program running on the Micromite Sharing the SPI channel is essentially transparent to the BASIC program see the description of the SPI communications function Appendix D in the Micromite Manual for a description of how to do this The following table lists the connections required between the LCD display board and the Micromite eege Description 2o pin npu Display Micromite Micromite T_IRQ Touch Interrupt Configurable T_DO Touch Data Out MISO Pin 14 Pin 41 T_DIN Touch Data In MOSI Pin 3 Pin 20 T_CS Touch Chip Select Configurable T_CLK Touch SPI Clock Pin 25 Pin 14 SDO MISO Display Data Out MISO Pin 14 Pin 41 LED Power supply for the backlight see below SCK Display SPI Clock Pin 25 Pin 14 SDI MOSI Display Data In MOSI Pin 3 Pin 20 D C Display Data Command Control Configurable RESET Display Reset when pulled low Configurable CS Display Chip Select Optional Configurable GND Ground VCC 5V s
79. e IRQ pin number that was specified when the touch facility was configured To detect touch down the interrupt should be configured as INTL ie high to low For example if the command OPTION TOUCH 7 15 was used to configure touch the following program will print out the X and Y coordinates of any touch on the screen SETPIN 15 INTL MyInt DO LOOP SUB MyInt PRINT TOUCH X TOUCH Y END SUB Note that once set up the interrupt cannot be cancelled ie SETPIN 15 OFF will not work Micromite User Manual Page 21 Using an LCD Panel There are eight basic drawing commands that you can use within MMBasic programs to interact with an attached LCD display All coordinates and measurements on the screen are done in terms of pixels with the X coordinate being the horizontal position and Y the vertical position The top left corner of the screen has the coordinates X 0 and Y 0 and the values increase as you move down and to the right of the screen Read Only Variables There are four read only variables which provide useful information about the display currently connected e MM HRES Returns the width of the display the X axis in pixels e MM VRES Returns the height of the display the Y axis in pixels e MM FONTHEIGHT Returns the height of the current default font in pixels All characters in a font have the same height e MM FONTWIDTH Returns the width of a character in the current defaul
80. e a different random sequence each time you must use a different value for nbr the TIMER function is handy for that RBOX xl yl w h Lr Le fill Draws a box with rounded corners on an attached LCD panel starting at x1 and y1 which is w pixels wide and H pixels high d is the radius of the corners of the box It defaults to 10 c specifies the colour and defaults to the default foreground colour if not specified fill is the fill colour It can be omitted or set to 1 in which case the box will not be filled See the section Basic Drawing Commands for a definition of the colours and graphics coordinates READ variable variable Reads values from DATA statements and assigns these values to the named variables Variable types ina READ statement must match the data types in DATA statements as they are read See also DATA and RESTORE REM string REM allows remarks to be included in a program Note the Microsoft style use of the single quotation mark to denote remarks is also supported and is preferred RESTORE line Resets the line and position counters for the READ statement If line is specified the counters will be reset to the beginning of the specified line line can be a line number or label If line is not specified the counters will be reset to the start of the program RETURN RETURN concludes a subroutine called by GOSUB and returns to the statement after the
81. e and low current drain The default speed on power up or reset is 4 0MHz The available clock speeds and typical current draw are CPU Speed Typical Current Draw 48MHz 31mA 40MHz default 26mA 30MHz 21mA 20MHz 15mA 10MHz 10mA SMHz 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 I C 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 The sleep current can be affected by many factors other than the base sleep current including connected USB and I C devices and current drawn by the I O pins which are maintained in their high low state during sleep 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
82. e it is possible to add user written features to MMBasic and make them permanent and part of the language For example you might have written a series of subroutines and functions that perform sophisticated bit manipulation these could be stored as a library and become part of MMBasic and perform the same as other built in functions that are already part of the language To install a library you need to write and test the routines as you would with any normal BASIC routines When you are satisfied that they are working correctly you can use the LIBRARY SAVE command This will transfer the routines as many as you like to a non visible part of flash memory where they will be available to any BASIC program but will not show when the LIST command is used and will not be deleted when a new program is loaded or NEW is used However the saved subroutines and functions can be called from within the main program and can even be run at the command prompt just like a built in command or function Some points to note e Library routines act exactly like normal BASIC code and can consist of any number of subroutines functions and CFunctions The only difference is that they do not show when a program is listed and are not deleted when a new program is loaded e Library routines can create and access global variables and are subject to the same rules as the main program for example respecting OPTION EXPLICIT if it is set e When the routines are transf
83. e it takes for the echo to be returned Compatible sensors are the SRFO5 SRFO6 Parallax PING and the DYP MEO007 which is waterproof and therefore good for monitoring the level of a water tank 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 the 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 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 r
84. e or two letters where the first letter is the horizontal justification around x and can be L C or R for LEFT CENTER RIGHT and the second letter is the vertical placement around y and can be T M or B for TOP MIDDLE BOTTOM The default justification is left top font and scale are optional and default to that set by the FONT command c is the drawing colour and BC is the background colour They are optional and default to the current foreground and background colours See the section Basic Drawing Commands for a definition of the colours and graphics coordinates TIME HH MM SS Sets the time of the internal clock MM and SS are optional and will default or to zero if not specified For example TIME 14 30 will set the clock to TIMES HH MM 14 30 with zero seconds ob The time is set to 00 00 00 on power up TIME HH TIMER msec Resets the timer to a number of milliseconds Normally this is just used to reset the timer to zero but you can set it to any positive integer See the TIMER function for more details TROFF Turns the trace facility off see TRON 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 var var or VAR RESTORE VAR SAVE will save one or more variables to non volatile flash memory where they
85. e pins will be returned to a not configured state They can then be configured as per normal using SETPIN SPI Open To use the SPI function the SPI channel must be first opened The syntax for opening the SPI or SPI2 channel is SPI OPEN speed mode bits Where e 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 e model is a single numeric digit representing the transmission mode see Transmission Format below e bits is the number of bits to send receive This can be 8 16 or 32 e Itis the responsibility of the program to separately manipulate the CS pin if required 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 0 is the most common format Mode Description CPOL CPHA 0 Clock is active high data is captured on the rising edge and output on the falling edge 0 0 1 Clock is active high data is captured on the falling edge and output on the rising edge 0 1 2 Clock is active low data is captured on the falling edge and output on the rising edge 1 0 3 Clock is active low data is captured on the rising edge and output on the falling edge 1 1 For a more complete explanation see http en wikipedia org wiki Serial_ Peripheral Interface Bus Standard Send Receive
86. ecks 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 Micromite User Manual Page 72 INPUT nbr fnbr Will return a string composed of nbr characters read from a serial communications port opened as fnbr This function will return as many characters as are waiting in the receive buffer up to nbr If there are no characters waiting it will immediately return with an empty string The is optional Also see the OPEN command INSTR start position string searched string pattern Returns the position at which string pattern occurs in string searched beginning at start position 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 CINTO LEFT S string nbr Returns a substring of string with nbr of characters from the left beginning of the string LEN string Returns the number of characters in string LOC fnbr For a serial communications port opened as fnbr this function will return the number of byt
87. ed 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 can 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 Following the restart the automatic variable MM WATCHDOG will 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
88. eed as discussed above Micromite User Manual Page 34 Defining and Using Variables Variables are a way for a program to store numbers or text MMBasic on the Micromite supports three different types of variables 1 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 Floating point variables are specified by adding the suffix to a variable s name eg i nbr etc They are also the default when a variable is created without a suffix eg 1 nbr etc 2 64 bit signed integer These can store positive or negative 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 1 nbr etc Note that during arithmetic operations particularly addition and multiplication no check is made for an overflow which may result in the final value requiring more than the number of digits supported In that case the result will be nonsense 3 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 Note that in previous versions of MMBasic it was legal to use the same variable name with different types and they
89. ements gt END SUB Defines a callable subroutine This is the same as adding a new command to MMBasic while it is running your program xxx is the subroutine name and it must meet the specifications for naming a variable arg1 arg2 etc are the arguments or parameters to the subroutine An array is specified by using empty brackets ie arg3 The type of the argument can be specified by using a type suffix ie arg1 or by specifying the type using AS lt type gt ie argl AS STRING Every definition must have one END SUB statement When this is reached the program will return to the next statement after the call to the subroutine The command EXIT SUB can be used for an early exit You use the subroutine by using its name and arguments in a program just as you would a normal command For example MySub al a2 When the subroutine is called each argument in the caller is matched to the argument in the subroutine definition These arguments are available only inside the subroutine Subroutines can be called with a variable number of arguments Any omitted arguments in the subroutine 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 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 subrou
90. ency include the Vishay TSOP4838 Jaycar ZD1952 and Altronics Z1611A Sony remotes use a 40KHz frequency but receivers for that frequency can be hard to find Generally 38KHz receivers will work but maximum sensitivity will be achieved with a 40KHz receiver To setup the decoder you use the command IR dev key interrupt Where dev is a variable that will be updated with the device code and key is the variable to be updated with the key code Interrupt is the interrupt subroutine to call when a new key press has been detected The IR decoding is done in the background and the program will continue after this command without interruption This is an example of using the IR decoder IR DevCode KeyCode IR_Int start the IR decoder DO lt body of the program gt LOOP SUB IR_Int a key press has been detected PRINT Received device DevCode key KeyCod END SUB IR remote controls can address many different devices VCR TV etc so the program would normally examine the device code first to determine if the signal was intended for the program and if it was then take action based on the key pressed There are many different devices and key codes so the best method of determining what codes your remote generates is to use the above program to discover the codes Micromite User Manual Page 25 The IR function uses the same I O pin as the wakeup signal for the CPU SLEEP com
91. er 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 DC or SPI to get data from a variety of sensors You can display data on low cost colour TFT LCD displays measure voltages detect digital inputs and drive output pins to turn on lights relays etc All from inside this cheap microcontroller Everything is internal to the Micromite and it will run from a couple of AA batteries The only extra component required is a 47uF capacitor The 28 pin dual in line version is particularly easy to use as it can be easily soldered and plugged into an IC socket Even better it costs just 4 In summary the features of the Micromite are A fast 32 bit CPU with 256K of flash and 64K RAM running a powerful BASIC interpreter 59KB 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 MMBasic allows the embedding of compiled C programs for high performance functions and the running program can be
92. er supply is as noise free as possible 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 gt SETPIN 15 FIN gt PRINT PIN 15 110374 gt In this case the frequency is 110 374 KHz Micromite User Manual Page 38 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 PINO 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 gt SETPIN 15 FIN 10 gt PRINT PIN 15 110300 gt 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
93. erial port and OPTION BAUDRATE used to set the required speed If you do this it might be worth using the OPTION BREAK command to disable the break key to prevent an unintended CTRL C in the console receive data from halting the running program Other useful options are OPTION CONSOLE NOECHO which will stop MMBasic from automatically echoing characters received on the console and OPTION CONSOLE INVERT which will invert the data on the transmit and receive lines so that it can be used with RS232 devices Resetting MMBasic MMBasic can be reset to its original configuration using either one of two methods e The chip can be reprogrammed with the Micromite firmware using a PIC32 programmer Micromite User Manual Page 15 e Sending a stream of exclamation marks to the console Rx pin at 34800 baud at startup If 30 of these characters are received in the first two seconds the Micromite will reset itself This can be accomplished by simply setting the terminal emulator to 38400 baud and holding down the exclamation key while powering up the Micromite on most keyboards this requires holding down shift and the number one key If the reset was successful the message MMBasic reset completed will display on the console 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 The LIBRARY Feature Using the LIBRARY featur
94. erred to the library space MMBasic will compress them by removing comments extra spaces blank lines and the hex codes in CFunctions This makes the library very space efficient Following the save the main program area is cleared e You cannot use multiple saves to the library space You must delete the library code see below before you can load a new library e You can use line numbers in the library but you cannot use a line number on an otherwise empty line as the target for a GOTO etc This is because the LIBRARY SAVE command will remove any blank lines e You can use READ commands in the library but they will default to reading DATA statements in the main program memory If you want to read from DATA statements in the library you must use the RESTORE command before the first READ command This will reset the pointer to the library space To delete the routines in the library space you use the LIBRARY DELETE command This will clear the space and return the flash memory used by the library back to the general pool used by normal programs The only other way to delete a library is to reset MMBasic to its original configuration as described above You can see what is in the library by using the LIBRARY LIST command which will list the contents of the library space In addition the MEMORY command can be used to display the amount of flash memory used by the library As an example you could save the following into the library CFunction CPU
95. es 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 Returns the natural logarithm of the argument number LCASES string Returns string converted to lowercase characters MIDS string start or MID amp string start nbr Returns a substring of string beginning at start and continuing for nbr characters The first character in the string is number 1 If nbr is omitted the returned string will extend to the end of string OCT number chars Returns a string giving the octal base 8 representation of number chars is optional and specifies the number of characters in the string with zero as the leading padding character s PEEK BYTE addr or PEEK WORD addr or PEEK VARADDR var or PEEK CFUNADDR cfun or 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
96. ession etc Same as above except that the output is directed to a serial communications port previously opened as nbr See the OPEN command PULSE pin width Will generate a pulse on pin with duration of width mS wd can be a fraction For example 0 01 is equal to 10uS and this enables the generation of very narrow pulses The minimum is 5uS at 40MHz to 40uS at SMHz 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 e pn must be configured as an output e For a pulse of less than 3 mS the accuracy is 1 us e For a pulse of 3 mS or more the accuracy is 0 5 mS e 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 PWM 1 freq 1A 1B or PWM 1 freq 1A 1B 1C or PWM 2 freq 2A Generate a pulse width modulated PWM output for driving analogue circuits sound output etc There are a total of five outputs designated as PWM in the diagrams on 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 controller
97. expression A 3 gt 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 Join two strings lt lt gt Se lt Inequality less than greater than less than or equal to less than or gt gt equal to alternative version greater than or equal to greater than or equal to alternative version 7 Equality String comparisons respect case For example A is greater than a Implementation Characteristics Maximum program size as plain text is 53KB 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 FOR NEXT loops is 10 Maximum number of nested DO LOOP commands is 10 Maximum number of nested GOSUBs subroutines and functions combined is 50 Maximum number of nested multiline IF ELSE ENDIF commands is 10 Maximum number of user defined subroutines and functions combined 100 Maximum number of interrupt pins that can be configured 10 Numbers are
98. ferred outside of the LOOP loop by commands like GOTO or RETURN if in a subroutine DO WHILE expression Loops while expression is true this is equivalent to the older WHILE lt statements gt WEND loop also implemented in MMBasic If at the start the expression LOOP is false the statements in the loop will not be executed even once DO Loops until the expression following UNTIL is true Because the test is lt statements gt made at the end of the loop the statements inside the loop will be executed at LOOP UNTIL expression least once even if the expression is false EDIT Invoke the full screen editor All the editing keys work with a VT100 terminal emulator so editing can also be accomplished over the console serial link The editor has been tested with Tera Term and PuTTY running on a Windows PC On entry the cursor will be automatically positioned at the last line edited or if there was an error when running the program the line that caused the error The editing keys are Left Right arrows Moves the cursor within the line Up Down arrows Moves the cursor up or down a line Page Up Down Move up or down a page of the program Micromite User Manual Page 54 Home End Moves the cursor to the start or end of the line A second Home End will move to the start or end of the program Delete Delete the character over the cursor This can be the line separator character and thus join two lines Backspace Dele
99. ge 11 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 unexpe
100. has expired If it has not this function will wait out the remainder of the conversion time before returning the value The DS18B20 can be powered separately by a 3V to 5V supply or it can operate on parasitic power from the Micromite See the section Special Hardware Devices for more details TOUCH X or TOUCH Y Will return the X or Y coordinate of the location currently touched on an LCD panel If the screen is not being touched the function will return 1 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 Returns the exponential value of number FIX number Truncate a number to a whole number by eliminating the decimal point and all characters to the right of the decimal point For example 9 89 will return 9 and 2 11 will return 2 The major difference between FIX and INT is that FIX provides a true integer function ie does not return the next lower number for negative numbers as INT does This behaviour is for Microsoft compatibility See also CINTO HEX number chars 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 Ch
101. he 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 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 ttme 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 Transfers a BASIC program to or from a remote computer using the XModem protocol The transfer is done over the serial console connection XMODEM SEND will send the current program held in the Micromite s program memory to the remote device XMODEM RECEIVE will accept a program sent by the remote device and save it into the Micromite s program memory overwriting the program currently held there Note that the data is buffered in RAM which limits the maximum program size
102. his function and multiple sensors can be used on different I O pins The value returned is the distance in centimetres to the target or 1 if no target was detected or 2 if there was an error ie sensor not connected The CPU speed must be 10OMHz or higher and the measurement can take up to 32mS to complete Micromite User Manual Page 71 RGB red green blue or RGB shortcut Generates an RGB true colour value red blue and green represent the intensity of each colour A value of zero represents black and 255 represents full intensity shortcut allows common colours to be specified by naming them The colours that can be named are white black blue green cyan red magenta yellow brown and gray For example RGB red or RGB cyan TEMPR pin Return the temperature measured by a DS18B20 temperature sensor connected to pin which does not have to be configured The CPU speed must be 1OMHz or above The returned value is degrees C with a default resolution of 0 25 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 interrupts will be ignored during this period Alternatively the TEMPR START command can be used to start the measurement and your program can do other things while the conversion is progressing When this function is called the value will then be returned instantly assuming the conversion period
103. ified an 8 bit address 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 DC 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 DC master This operates the same as a general interrupt on an external TO pin UO Pins Refer to pinout charts at the beginning of this manual for the pin numbers used for the I C data line SDA and clock SCL Both of these pins
104. ile can be sent to someone as custom firmware for a compatible PIC32 chip They can load the hex file and it will immediately start running your program To them it will be indistinguishable from firmware written in C other than the startup banner produced by MMBasic They do not have to load MMBasic and they do not need know anything about programming for the Micromite Micromite User Manual Page 18 LCD Displays MMBasic version 5 0 and later includes support for colour LCD display panels using the ILI9341 controller and an SPI interface These have a 240x320 pixel colour TFT display come in a variety of sizes 2 2 2 4 and 2 8 and are low cost typically US 8 On eBay you can find suitable displays by searching for the controller name ILI9341 There are many similar displays on the market however some have subtle differences that could prevent them from working with the Micromite MMBasic was tested with the displays illustrated below so if you wish to guarantee success make sure your display matches the photographs and the specifications listed below The ILI9341 based displays use an SPI interface and have the following basic specifications e A2 2 2 4 or 2 8 inch display e Resolution of 240 x 320 pixels and a colour depth of 262K 65K e AILI9341 controller with a SPI serial interface The display illustrated also has a touch sensitive facility which is fully supported by MMBasic There are versions of this display without th
105. ill also be made to the supplied variable This is called passing arguments by reference For example you might define a subroutine to swap two values as follows SUB Swap a b LOCAL t ba az D bs t END SUB In your calling program you would use variables for both arguments Swap nbril nbr2 And the result will be that the values of nbr1 and nbr2 will be swapped Unless you need to return a value via the argument you should not use an argument as a general purpose variable inside a subroutine or function This is because another user of your routine may unwittingly use a variable in their call and that variable will be magically changed by your routine It is much safer to assign the argument to a local variable and manipulate that instead 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 arrays 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
106. in various ways see the I2C WRITE commands for details I2C SLAVE READ revlen Receive data from the UC master device This command should be used in rcvbuf revd the receive interrupt ie in the rcv_int subroutine when the master has sent some data Alternatively a flag can be set in the receive interrupt subroutine and the command invoked from the main program loop when the flag is set revlen 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 revlen must be 1 rcvd will contain the actual number of bytes received by the command I2C SLAVE CLOSE Disables the slave UC 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 I C write or read command the automatic variable MM DC 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 I C protocol is generally compatible with previous versions with the following differences e The commands have been renamed but have the same functionality I2CEN is now DC OPEN I2CSEND is I2C WRITE I2CRCV is I2C READ and I2CDIS i
107. inactive INTH Interrupt on low to high input INTL Interrupt on high to low input INTB Interrupt on both ie any change to the input target is a user defined subroutine which will be called when the event happens Return from the interrupt is via the END SUB or EXIT SUB Micromite User Manual Page 67 Commande 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 pull up or down is about 100K If option is omitted the input will be high impedance This mode also configures the pin as a digital input so the value of the pin can always be retrieved using the function PINO Refer to the section Using the I O pins for a general description of the Micromite s input output capabilities SETTICK period target nbr This will setup a periodic interrupt or tick Four tick timers are available nbr 1 2 3 or 4 nbr is optional and if not specified timer number 1 will be used The time between interrupts is period milliseconds and target is the interrupt subroutine which will be called when the timed event occurs The period can range from 1 to 2147483647 mSec about 24 days These interrupts can be disabled by setting period to zero ie SETTICK 0 0 3 will disable tick timer number 3 SUB xxx arg arg2 lt statements gt lt stat
108. inal Absolute maximum 4 0V 93mA to 6mA depending on the clock speed 90uA to 100A plus current draw from the I O pins 0 to 0 65V 2 5V to 3 3V on normal pins 2 5V to 5 5V on pins rated at 5V gt 1MQ All digital inputs are Schmitt Trigger buffered Up to 300KHz pulse width 20nS or more on the counting inputs pins 15 to 18 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 gt 1MQ for accurate readings the source impedance should be lt 5K Typical current draw or sink ability on any I O pin 10mA Absolute maximum current draw or sink on any I O pin 15mA Absolute maximum current draw or sink for all I O pins combined 200mA Maximum open collector voltage 5 5V Timing Accuracy All timing functions the timer tick interrupts PWM frequency baud rate etc are dependent on the internal clock The Micromite uses a fast RC oscillator which has a specified tolerance of 0 9 but typically is within 0 1 at 24 C PWM Output Frequency range Duty cycle 20Hz to 500KHz 0 to 100 with 0 1 resolution below 25KHz Serial Communications Ports Console COM ports Default 38400 baud Range is 100 bps to 230400 bps at 40MHz Micromite Default 9600 baud Range is 10 bps to 230400 bps at 40MH2 The maximum is limited by the clock speed See Appendix A for details Other Commu
109. inal emulator to the Micromite and have the command prompt the greater than symbol as shown above ie gt 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 gt PRINT 1 7 0 142857 gt 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 e At the command prompt type EDIT followed by the ENTER key e The editor should start up and you can enter this line PRINT Hello World e 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 e At the command prompt type RUN followed by the ENTER key e You should see the message Hello World 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 A DO 15 PIN 15 1 PAUSE 300 82 LED PIN 15 0 ohms PAUSE 300 LOOP When y
110. ine GOSUB based on the rounded value of nbr if it is 1 the first target is called if 2 the second target is called etc Target can be a line number or a label ON KEY target Setup an interrupt which will call target user defined subroutine whenever there is one or more characters waiting in the serial console input buffer Note that all characters waiting in the input buffer should be read in the interrupt subroutine 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 Micromite User Manual Page 60 OPEN comspec AS fnbr 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 OPTION AUTORUN OFF ON Instruct MMBasic to automatically run the program stored in flash when it starts up or is restarted by the WATCHDOG command This is turned off by the NEW command but other commands that might change program memory EDIT etc do not change this setting Entering the break key default CTRL C at the console will interrupt the running program and return to the command prompt OPTION BASE 01 1 Set the lowest value f
111. ine or function Note e LOCAL can only be used in a subroutine or function e It uses exactly the same syntax as DIM LOOP UNTIL expression Terminates a program loop see DO MEMORY List the amount of memory currently in use For example Flash 21K 35 Program 805 lines 1K 1 2 CFunctions 1K 1 4 Saved Variables 37K 63 Free RAM 9K 16 5 Variables 18K 32 General 26K 52 Free Notes e General memory is used by serial I O buffers etc e Program memory is cleared by the NEW command e Variables and the general memory spaces are cleared by many commands eg NEW RUN etc as well as the specific commands CLEAR and ERASE e Memory usage is rounded to the nearest 1K byte e When a program is loaded it is first buffered in RAM which limits the maximum program size MMBasic tokenises the program when it is stored in flash so the final size in flash might vary from this NEW Deletes the program in flash and clears all variables NEXT counter variable counter variable etc NEXT comes at the end of a FOR NEXT loop see FOR The counter variable specifies exactly which loop is being operated on If no counter variable is specified the NEXT will default to the innermost loop It is also possible to specify multiple counter variables as in NEXT x y z ON nbr GOTO GOSUB target target target ON either branches GOTO or calls a subrout
112. ing 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 Micromite User Manual Page 12 Shortcut Keys When you are using a VT 100 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 Micromite User Manual Page 13 Micromite Special Features Saved Variables Because the Micromite does not necessarily have a normal storage system such as an SD card it needs to have a facility to save some data that can be recovered when power is restored This can be done with the VAR SAVE command which will take up to fifty variables on its command line and will save their values in non volatile flash memo
113. iode may be omitted for I O pins that are not 5V tolerant as they have a built in clamping diode to the 3 3V rail Micromite User Manual Page 81 Appendix B 2 i TC Communications The Inter Integrated Circuit UC bus was developed by Philips now NXP for the transfer of data between integrated circuits This implementation was written by Gerard Sexton and the standard definition of UC is provided by this document http www nxp com documents user_manual UM10204 pdf There are four commands that can be used in DC master mode DC OPEN speed timeout Enables the DC module in master mode PU speed is a value between 10 and 400 for bus speeds 10 kHz to 400 kHz timeout is a value in milliseconds after which the master send and receive commands will be interrupted if they have not completed The minimum value is 100 A value of zero will disable the timeout though this is not recommended DUT if specified will enable weak pullups about 100K on both the clock and data lines DC normally requires lower value resistors typically 10K but for short signal lines at slow speed this may be all that is required I2C WRITE addr option Send data to the IC slave device sendlen senddata sendata addr is the slave PC address we option is a number between 0 and 3 normally this is set to 0 1 keep control of the bus after the command a stop condition will not be sent at the completion of the command
114. isabled until the interrupt subroutine returns During an interrupt and at all times the value of the interrupt pin can be accessed using the PINO 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 TEMPR 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 30uS 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 Note that the old standard of an interrupt jumping to a line number or label is still supported in MMBasic although calling a subroutine is cleaner and easier to document so it should be used in preference If the interrupt destination is a line number or label the interrupt routine must be terminated with an IRETURN command which will return control to the main program Micromite User Manual Page 40 Timing MMBasic has a number of features that make it easy to time events and control external circuitry that needs timing MMBasic maintains a
115. ive lines This allows the console to be used with RS232 signals without a converter see the section Low Cost RS 232 Interface in Appendix A It NOINVERT also allows the use of a PICAXE style programming cable or NOINVERT will restore the console to its normal operation and is the default OPTION CONSOLE AUTO AUTO will automatically invert the data polarity on the console depending on the signal level at power up a low input means that the console will be inverted This will automatically switch between TTL serial and RS232 serial input Note that there is a 200mS startup delay when AUTO is used This option will be remembered even when the power is removed OPTION DEFAULT FLOAT Used to set the default type for a variable which is not explicitly defined INTEGER STRING NONE 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 OPTION DISPLAY lines chars 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
116. lue Executes one of several groups of statements depending on the value of an CASE testexp testexp expression lt statements gt value is the expression to be tested It can be a number or string variable or lt statements gt a complex expression CASE ELSE testexp is the value that exp is to be compared against It can be lt statements gt e A single expression ie 34 string or PIN 4 5 to which it may equal lt statements gt e A range of values in the form of two single expressions separated by the END SELECT keyword TO ie 5 TO 9 or aa TO cc e Acomparison starting with the keyword IS which is optional For example IS gt 5 IS lt 10 If value cannot be matched with a testexp it will be automatically matched to the CASE ELSE If CASE ELSE is not present the program will not execute any lt statements gt and continue with the code following the END SELECT When a match is made the lt statements gt following the CASE statement will be executed until END SELECT or another CASE is encountered when the program will then continue with the code following the END SELECT An unlimited number of CASE statements can be used but there must be only one CASE ELSE and that should be the last before the END SELECT Each SELECT CASE must have one and one only matching END SELECT statement Any number of SELECT CASE statements can be nested inside the CASE statements of other SELECT CASE statemen
117. m that the contacts are indeed closed A simpler solution is to connect a 100nF capacitor across the switch contacts as illustrated above 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 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 lt lt Y E A standard encoder has two outputs labelled RA and RB and a common re ground The outputs should be wired with pullup resistors as shown below SI 3 3V er S d a be And this program fragment can be used to decode the output SETPIN 3 DIN setup RB as an input SETPIN 2 INTH RInt setup an interrupt when RA goes high DO lt main body of the program gt LOOP SUB RInt Interrupt to decode th ncoder output F PIN 3 1 then Value Value 1 IT clockwise rotation ELSE Value Value 1 anti clockwise rotation ENDIF END SUB This program assumes that the encoder is connected to I O pins 2 and 3 on the Micromite however any pins can
118. mand 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 SUB IR_Int a key press has been detected lt do some work based on the key press gt END SUB return to sleep again Infrared Remote Control Transmitter Using the IR SEND command you can transmit a 12 bit 3 3V 5V Sony infrared remote control signal This is intended for Micromite to Micromite communications but it will also work with Sony equipment that uses 12 bit codes Note that all Sony products require that the message be sent three times with a 26mS delay between each message The circuit on the right illustrates what is required The transistor is used to drive the infrared LED because the output of the Micromite is limited to about 10mA This Micromite circuit provides about 50mA to the LED To send a signal you use the command IR SEND pin dev cmd Where pin is the I O pin used dev is the device code to send and key is the key code Any I O pin on the Micromite can be used and you do not have to set it up beforehand the IR SEND BEE will automatically do
119. ming data the serial port will automatically discard the oldest data to make room for the new data Serial ports can be closed with the CLOSE command This will discard any characters waiting in the buffers free the memory used by the buffers cancel the interrupt if set and set all pins used by the port to the not configured state A serial port is also automatically closed when commands such as RUN and NEW are issued Interrupts The interrupt subroutine if specified will operate the same as a general interrupt on an external I O pin see the section Using the I O pins for a description 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 subroutine can read the data In this case the buffer should be increased to 512 characters or more Additional Serial Ports Additional serial ports can be added to the Micromite by using the SerialTx and SerialRx embedded C modules These are included in the Embedded C Modules folder in the Micromite firmware zip file Micromite User Manual Page 79 IEEE 485 The DE option in the OPEN comspec for COM1 specifies that the Data output Enable ENABLE signal for the IEEE
120. mite Note that the physical pins on the chip and the pin numbers used in MMBasic are the same This means that eleven pins are not available in MMBasic these pins are shaded in grey Pin 34 SE Ki a A Pinl Pin Pin ANALOG DIGITAL PWM IC 23 22 PWM 1B DIGITAL ANALOG ANALOG DIGITAL COM1 ENABLE 24 21 PWM 1A DIGITAL ANALOG ANALOG DIGITAL 25 20 SPI OUT MOSI DIGITAL ANALOG ANALOG DIGITAL 26 19 DIGITAL ANALOG ANALOG DIGITAL 27 18 RESET Wired to V directly or via 10K resist POWER 2 3 to 3 6V 28 17 ANALOG POWER 2 3 to 3 6V GROUND 29 16 ANALOG GROUND DIGITAL COM2 TRANSMIT 30 15 PWM 2A DIGITAL ANALOG DIGITAL COM2 RECEIVE 31 14 SPI CLOCK DIGITAL ANALOG DIGITAL 5V 32 13 5V DIGITAL CONSOLE Tx DATA OUT 33 12 5V DIGITAL Koch CONSOLE Rx DATA IN 34 PWM 2B DIGITAL ANALOG DIGITAL 5V 35 10 DIGITAL ANALOG DIGITAL 36 9 COM1 RECEIVE 5V DIGITAL DIGITAL 5V 37 8 COM1 TRANSMIT 5V DIGITAL DIGITAL 5V 38 7 47uF TANT CAPACITOR GROUND 39 6 GROUND POWER 2 3 to 3 6V 40 5 5V DIGITAL DIGITAL 5V SPIIN MISO 41 4i 5V DIGITAL DIGITAL 5V COUNT 42 3 5V DIGITAL DIGITAL 5V COUNT WAKEUP IR 43 2 5V_ DIGITAL DIGITAL 5V COUNT PC CLOCK 44 1 PCDATA COUNT 5V_ DIGITAL The notation is the same as described for the 28 pin version Micromite User Manual Page 8
121. must be first set That is done with the Micromite User Manual Page 27 RTC SETTIME command which uses the format RTC SETTIME year month day hour minute second Note that the year is just the last two digits ie 15 for 2015 and hour is in 24 hour format For example the following will set the real time clock to 4PM on the 10 November 2016 RTC SETTIME 16 11 10 16 O 0 To get the time you use the RTC GETTIME command which will read the time from the real time clock chip and set the clock inside the Micromite Normally this command will be placed at the beginning of the program or in the subroutine MM STARTUP so that the time is set on power up The clock in the standard 28 and 44 pin Micromite can drift by up to two or three seconds in an hour so to keep it over a long period the RTC can be polled at regular intervals using the SETTICK command For example RTC GETTIME set the time at startup SETTICK 12 3600000 SetTime 4 interrupt every 12 hours lt normal program gt SUB SetTime interrupt called every 12 hours RTC GETTIME reset the tim END SUB Measuring Distance Using a HC SR04 ultrasonic sensor and the DISTANCEQ 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 Gan sound pulse and measuring the tim
122. n 123 456 STR 123 456 6 willreturn 123 456 STR 123 456 6 5 willreturn 123 45600 STR 53 6 STR 53 6 2 STR 53 6 2 will return 53 will return 53 00 will return 53 00 STRING nbr ascii or STRINGS nbr string 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 Micromite User Manual Page 75 TAB number Outputs spaces until the column indicated by number has been reached TAN number Returns the tangent of the argument number in radians 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 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 it is a 64 bit number and will only roll over to zero after 200 million years UCASES string Returns string converted to uppercase characters VAL string Returns the numerical value of the string If string is an invalid number the function will return zero
123. n be used in the same manner as a built in command or function This command specifies the hex codes for the module This code is 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 Micromite User Manual Page 50 or CFUNCTION name hex hex hex hex END CFUNCTION e Each bes 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 CSUB or END CFUNCTION e The first hex word must be the offset in 32 bit words to the entry point of the embedded routine usually the function main e Multiple embedded routines can be used in a program with each defining a different module with a different name e During execution MMBasic will skip over any CSUB or 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 name created by these commands can be used as a normal command or function within MMBasic with a few caveats e If CFUNCTION is used the function will always return an integer e Up to ten values can be specified as parameters arg1 arg2 etc and they will be passed to the embedded C routine as pointers to the memory space allocated to each value ie the result of the expression e If a variable or array is specified as an
124. n 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 I C 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 20uS 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 l
125. nction to get the temperature described above 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 5381 and 5383 go to www altronics com To enable the keypad feature you use the command KEYPAD Vat gt ints tly Eier nse T p Cly CZy Es C4 Where var is a variable that will be updated with the key code and int is the name of the interrupt subroutine 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 cl 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 Micromite User Manual Page 29 3 3V Micromite 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 ci
126. nd for details on how to use the library The default font used by MMBasic is font 1 however that can be changed with the FONT command FONT font number scaling Where font number is a number which can be optionally preceded by a hash character scaling is optional and is a number in the range of 1 to 15 The font will be multiplied by the scaling factor making the displayed character correspondingly wider and taller For example specifying scaling of 2 will double the height and width If not specified the scaling factor will be 1 ie no scaling Drawing Commands Most drawing commands have optional parameters You can completely leave these off the end of a command or you can use two commas in sequence to indicate a missing parameter For example the fifth parameter of the LINE command is optional so you can use this format LINE 0 0 100 100 rgb red Optional parameters are indicated in this document by italics for example font In the following commands C is the drawing colour and defaults to the current foreground colour FILL is the fill colour which defaults to 1 which indicates that no fill is to be used The drawing commands are CLS C Clears the screen to the colour C If C is not specified the current default background colour will be used PIXEL X Y C Illuminates a pixel If C is not specified the current default foreground colour will be used LINE X1 Y1 X2 Y2 IW
127. ng 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 o 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 IM 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 Ifa multi dimensioned array is initialised then the first dimension will be initialised first followed by the second etc iw or DO This structure will loop forever the EXIT DO command can be used to lt statements gt terminate the loop or control must be explicitly trans
128. ng polarity is inverted with respect to TTL On the Micromite COM1 can be specified to invert the transmit and receive signal the INV option so that is an easy fix For the receive data that is the 12V signal from the remote RS 232 device it is easy to limit the voltage using a series resistor of say 22KQ and a diode that will clamp the positive voltage to the 3 3V rail The input impedance of the Micromite is very high so the resistor will not cause a voltage drop but it does mean that when the signal swings to the maximum 12V it will be safely clipped by the diode and when it swings to 12V it will be clipped by the protection diode internal to the Micromite For the transmit signal from the Micromite to the RS 232 device you can connect this directly to the input of the remote device The Micromite will only swing the signal from zero to 3 3V but most RS 232 inputs have a threshold of about 1V so the Micromite s signal will still be interpreted as a valid signal Micromite User Manual Page 80 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 3 3V 1N4001 or similar RS 232 Device Transmit Data Micromite RS 232 Device Receive Data Signal Ground And open COM1 with the invert option For example OPEN COM1 4800 INV AS 1 Note that the clamping d
129. nications Ports SPI re 1 Wire Flash Endurance 10Hz to 1OMHz at 40MHz Limited to one quarter of the clock speed 10KHz to 400KHz Fixed at 15KHz 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 User Manual Page 46 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 foll
130. nications labelled COM1 and COM2 After being opened they will have an associated file number and you can use any commands that operate with a file number to read and write to from the serial port A serial port is also closed using the CLOSE command The following is an example OPEN COM1 4800 AS 5 open the first serial port with a speed of 4800 baud PRINT 5 Hello send the string Hello out of the serial port dat INPUTS 20 5 get up to 20 characters from the serial port CLOSE 5 close the serial port The OPEN Command A serial port is opened using the command OPEN comspec AS fnbr fnbr is the file number to be used It must be in the range of 1 to 10 The is optional comspec is the communication specification and is a string it can be a string variable specifying the serial port to be opened and optional parameters The default is 9600 baud 8 data bits no parity and one stop bit Ithas the form COMn baud buf int intlevel DE 9BIT INV OC S2 where e m is the serial port number for either COM1 or COM2 e baud is the baud rate see Baud Rate below for the limits in the speed Default is 9600 e buf is the receive buffer size in bytes default size is 256 The transmit buffer is fixed at 256 bytes e int is a user defined subroutine which will be called when the serial port has received some data The default is no interrupt e intlevel is the
131. od programming practice If it is used it should be placed at the start of the program before any variables are used DIM and LOCAL The DIM and LOCAL commands can be used to define a variable and set its type and are mandatory when the OPTION EXPLICIT command is used The DIM command will create a global variable that can be seen and used throughout the program including inside subroutines and functions However if you require the definition to be visible only within the subroutine or function you should use the LOCAL command LOCAL has exactly the same syntax as DIM If LOCAL is used to specify a variable with the same name as a global variable then the global variable will be hidden to the subroutine or function and any references to the variable will only refer to the variable defined by the LOCAL command At its simplest level DIM and LOCAL can be used to define one or more variables based on their type suffix or the OPTION DEFAULT in force at the time For example DIM nbr strs But it can also be used to define one or more variables with a specific type when the type suffix is not used DIM INTEGER nbr nbr2 nbr3 etc In this case nbr nbr2 nbr3 etc are all created as integers When you use the variable within a program you do not need to specify the type suffix For example the following works as expected nbr2 12345678 The DIM and LOCAL commands will also accept the Microsoft practice of specifying the
132. onds 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 90uA to 1004A 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 see the pinout tables at the start of this manual 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 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 e 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 40MHz to 1mS at SMHz The I O pins will remain active and any that are set as outputs will continue to source or draw current depending on their state and attached components This should be considered when trying to reduce the current drain during sleep All timing functions will f
133. ons Any free pin can be used CS pin can also be any I O pin but is optional If a touch controller is not used this parameter can be left off the command and the CS pin on the LCD display wired permanently to ground If the touch controller is used this pin must then be specified and connected to a Micromite I O pin This command only needs to be run once as the parameters are stored in non volatile memory Every time the Micromite is restarted MMBasic will automatically initialise the display ready for use If the LCD panel is no longer required the command OPTION LCDPANEL DISABLE can be used which will disable the LCD panel feature and return the I O pins for general use To test the display you can enter the command GUI TEST LCDPANEL You should see an animated display of colour circles being rapidly drawn on top of each other Press any key on the console s keyboard to stop the test Important The above test may not work if the display has a touch controller and the touch controller has not been configured ie the touch Chip Select pin is floating In this case configure the touch controller see below and then retry GUI TEST LCDPANEL NOTE The CPU speed must be 20MHz or greater To verify the configuration you can use the command OPTION LIST to list all options that have been set including the configuration of the LCD panel Loadable Drivers You can use a loadable driver to add full support for LCD panels using other controllers The
134. ons of each I O pin on the Micromite Note that the physical pins on the chip and the pin numbers used in MMBasic are the same This means that nine pins are not available in MMBasic as they are dedicated to functions such as power and ground These pins are shaded in grey in the diagram RESET Wired to V directly or via 10K resist DIGITAL ANALOG SPI OUT DIGITAL ANALOG PWM 1A DIGITAL ANALOG PWM 1B DIGITAL ANALOG PWM 1C DIGITAL ANALOG COMI ENABLE DIGITAL ANALOG GROUND COM TRANSMIT DIGITAL COM RECEIVE DIGITAL CONSOLE Tx DATA OUT CONSOLE Rx DATA IN POWER 2 3 to 3 6V SPIIN 5V DIGITAL ANALOG POWER 2 3 to 3 6V ANALOG GROUND ANALOG DIGITAL PWM 2A ANALOG DIGITAL SPI CLOCK ANALOG DIGITAL PWM 2B ANALOG DIGITAL DIGITAL 5V COM1 RECEIVE DIGITAL 5V COM1 TRANSMIT 47uF TANT CAPACITOR GROUND DIGITAL 5V COUNT PCDATA DIGITAL 5V COUNT PC CLOCK DIGITAL 5V COUNT WAKEUP IR DIGITAL 5V COUNT 1 2 3 4 5 6 7 8 9 e ae oS RW N ra O 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 including digital input DIN and digital output DOUT 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
135. onts can be embedded in a BASIC program The MMBasic firmware zip file includes over a dozen embedded fonts covering a wide range of character sets and includes symbol fonts Dingbats which are handy for creating on screen icons etc These fonts work exactly same as the built in fonts ie selected using the FONT command or specified in the TEXT command The format of an embedded font is DefineFont Nbr hex best hex best END DefineFont It must start with the keyword DefineFont followed by the font number which may be preceded by an optional character Any font number in the range of 1 to 16 can be specified The body of the font is a sequence of 8 digit hex words with each word separated by one or more spaces or a new line The font definition is terminated by an End DefineFont keyword Micromite User Manual Page 22 When a BASIC program is saved to program memory MMBasic will search through it looking for any embedded fonts and the font table will be updated to include them During execution embedded fonts will be skipped over and this means that they can be placed anywhere in the program Embedded fonts can also be saved to the library area When this is done the font is for all intent and purposes permanently added to the MMBasic language In addition MMBasic will strip out the hex codes in the font definition because they are no longer needed and this will save a considerable amount of memory See the LIBRARY comma
136. oop LOOP SUB DOINT tick interrupt PRINT TIMES PIN 2 END SUB 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 Micromite User Manual Page 41 Defined Subroutines and Functions Defined subroutines and functions are useful features to help in organising programs so that they are easy to modify and read A defined subroutine or function is simply a block of programming code that is contained within a module and can be called from anywhere within your program It is the same as if you have added your own command or function to the language For example assume that you would like to have the command FLASH added to MMBasic its job would be to flash a LED on pin 2 You could define a subroutine like this SUB FLASH SETPIN 2 DOUT PIN 2 1 PAUSE 100 PIN 2 0 END SUB Then in your program you just use the command FLASH to flash the LED For example IF A lt B T
137. or array subscripts to either 0 or 1 This must be used before any arrays are declared and is reset to the default of 0 on power up OPTION BAUDRATE nbr 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 on the 28 and 44 pin Micromites This oscillator is used as the basis for all timing eg date time pause PWM freq
138. ou 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 Setting the AUTORUN Option You now have the Micromite doing something useful if you can call flashing a LED useful Assuming that this is all that you want the Micromite to do you can then instruct it to always run this program whenever power is applied To do this you first need to regain the command prompt and you can do this by entering CTRL C at the console This will interrupt the running program and return you to the command prompt Then enter the command OPTION AUTORUN ON This will instruct MMBasic to automatically run your program whenever power is applied To test this you can remove the power and then re apply it The Micromite should start up flashing the LED If this is all that you want you can disconnect the serial console and it will sit there flashing the LED on and off forever If ever you wanted to change something for example the pause between on and off you could attach your terminal emulator to the console interrupt the program with a CTRL C and edit it as needed This is the great benefit of the Micromite it is very easy to write and change a program Micromite User Manual Pa
139. ouble quote marks Eg Hello World Operators and Precedence The following operators in order of precedence are recognised Operators that are on the same level for example and are processed with a left to right precedence as they occur on the program line Arithmetic operators A Exponentiation MOD Multiplication division integer division and modulus remainder Addition and subtraction Shift operators X lt lt y xX gt gt y These operate in a special way lt lt means that the value returned will be the value of x shifted by y bits to the left while gt gt 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 logical inverse of the value on the right lt lt gt Se lt Inequality less than greater than less than or equal to less than or gt gt equal to alternative version greater than or equal to greater than or equal to alternative version 7 equality AND OR XOR Conjunction disjunction exclusive or Micromite User Manual Page 47 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 gt 5 will print the number zero on the output and the
140. ound 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 Micromite User Manual Page 39 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 Any I O pin that can be used as a digital input can be configured to generate an interrupt using the SETPIN command with up to ten interrupts 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 the specified user defined subroutine The target can be the same or different for each interrupt Return from an interrupt is via the END SUB or EXIT SUB commands Note that no parameters can be passed to the subroutine however within the interrupt subroutine calls to other subroutines are allowed If two or more interrupts occur at the same time they will be processed in order of the interrupts as defined with SETPIN During the processing of an interrupt all other interrupts are d
141. 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 pull up voltage in this mode is 5 5V Pulse Width Modulation The PWM Pulse Width Modulation command allows the Micromite to generate square waves with a program controlled duty cycle By varying the duty cycle you can generate a program controlled voltage output for use in controlling external devices that require an analog input power supplies motor controllers etc The PWM outputs are also useful for driving servos and for generating a sound output via a small transducer There are two PWM controllers the first has three outputs and the second two to give a total of five PWM outputs The frequency of each controller can be independently set from 20Hz to 500KHz and the duty cycle for each output ie five outputs can also be independently set from between 0 and 100 with a 0 1 resolution when the frequency is below 25KHz above 25KHz the resolution is 1 or better up to 250KHz 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 gr
142. owing the decimal point These are specified by adding the suffix to a variable s name For example 1 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 amp H for a hexadecimal constant amp O for an octal constant or amp B for a binary constant For example amp B1000 is the same as the decimal constant 8 Constants that start with amp H amp O or amp 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 d
143. pression to the variable LET is automatically assumed if a statement does not start with a command LCD INIT d4 d5 d6 d7 rs en or LCD line pos text or LCD CLEAR or LCD CLOSE 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 dai to d7 are the I O pins that connect to inputs D4 to D7 on the LCD module inputs DO to D3 should be connected to ground rel 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
144. preter 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 L or for float integer or string For example DIM nbr5 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 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 names amount last_name city 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
145. r Manual Page 87 Appendix C 1 Wire Communications The 1 Wire protocol was developed by Dallas Semiconductor to communicate with chips using a single signalling line This implementation was written for MMBasic by Gerard Sexton There are three commands that you can use ONEWIRE RESET pin Reset the 1 Wire bus ONEWIRE WRITE pin flag length data data Send a number of bytes ONEWIRE READ pin flag length data data Get a number of bytes 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 Returns true if a device was found Note The CPU speed must be 1OMHz or above After the command is executed the I O pin will be set to the not configured state unless flag option 8 is used When a reset is requested the automatic variable MM ONEWIRE will return true if a device was found This will occur with the ONEWIRE RESET command and the ONEWIRE READ and ONEWIRE WRITE commands if a reset was requested flag 1 or 2 For users of MMBasic on earlier device
146. r example PORT 15 4 23 4 amp B10000011 Will set eight I O pins Pins 15 and 16 will be set high while 17 18 23 24 and 25 will be set to a low and finally 26 will be set high This command can be used to conveniently communicate with parallel devices like LCD displays Any number of I O pins and therefore bits can be used from 1 to 23 pins See the PORT function to simultaneously read from a number of pins PRINT expression IL Jexpression etc Outputs text to the serial console Multiple expressions can be used and must be separated by either a e Comma which will output the tab character e Semicolon which will not output anything it is just used to separate expressions e 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 PRINT nbr expression L expr
147. racter 1 or 0 indicating the state of the OI 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 9 bit the first character and then take the appropriate action with the second character For example IF LOC 1 gt 2 THEN check that we have at least two bytes AS INPUTS 1 1 BS INPUTS 1 1 IF AS 1 THEN BS contains an address ELSE BS 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 Low Cost RS 232 Interface The RS 232 signalling system is used by modems hardwired serial ports on a PC test equipment etc It is the same as the serial TTL system used on the Micromite with two exceptions e The voltage levels of RS 232 are 12V and 12V where TTL serial uses 3 3V and zero volts e The signalling is inverted the idle voltage is 12V the start bit is 12V etc It is possible to purchase cheap RS 232 to TTL converters on the Internet but it would be handy if the Micromite could directly interface to RS 2372 The first issue is that the signalli
148. rcles 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 lt body of the program gt LOOP SUB KP_Int a key press has been detected PRINT Key press KeyCod END SUB Switch Inputs Often there is a need to use a switch as an input to a Micromite based 3 3V project This is easy to implement as a Micromite 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 H and the 3 3V supply it is about 100K ae This means that the switch can be connected between the ground and i 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 Micromite To specify a pullup resistor you use SETPIN as follows MkII 100nF 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 to the momentum of the Micromite User Manual Page 30 mechanical assembly Because the 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 confir
149. 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 The Serial Console 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 Once changed the console baud rate will be permanently remembered unless another OPTION BAUDRATE command is used to change it Using this command it is possible to accidently set the baud rate to an invalid speed and in that case the only recovery is to reset MMBasic as described below When running as an embedded controller the serial console may no longer be required for programming On the standard Micromite it can then be used as a third s
150. reeze during the sleep this includes the real time clock and background pulse commands e CTRL C on the console will not bring the chip out of sleep CPU RESTART Will force a restart of the processor This will clear all variables and reset everything eg timers COM ports I C etc similar to a power up situation but without the power up banner If OPTION AUTORUN has been set the program in memory will restart DATA constant constant Stores numerical and string constants to be accessed by READ In general string constants should be surrounded by double quotes An exception is when the string consists of just alphanumeric characters that do not represent MMBasic keywords such as THEN WHILE etc In that case quotes are not needed Numerical constants can also be expressions such as 5 60 DATE DD MM YY or DATE DD MM YY Set the date of the internal clock calendar DD MM and YY are numbers for example DATE 28 7 2014 The date is set to 1 1 2000 on power up Micromite User Manual Page 52 DEFINEFONT Nbr hex hex hex hex END DEFINEFONT This will define an embedded font which can be used alongside or to replace the built in font s used on an attached LCD panel These work exactly same as the built in fonts ie selected using the FONT command or specified in the TEXT command Nbr is the font s reference number from 1 to 16 It can be the
151. reseeds the random number generator SGN number Returns the sign of the argument number 1 for positive numbers 0 for 0 and 1 for negative numbers SIN number Returns the sine of the argument number in radians SPACE number Returns a string of blank spaces number bytes long SQR number Returns the square root of the argument number STR number Returns a string in the decimal base 10 representation of number or If m is specified sufficient spaces will be added to the start of the number to STR number m ensure that the number of characters before the decimal point including the ee negative sign will be at least m characters If m is zero or the number has more than m significant digits no padding spaces will be added STR number m n E SS If m is negative the plus symbol will be added to the start of positive or STR number m n c numbers and then padded with leading spaces if required n is the number of digits required to follow the decimal place The maximum value is seven and if n is zero the string will be returned without the decimal point If n is not specified then the number of decimal places will vary according to the number c is a string and if specified the first character of this string will be used as the padding character instead of a space see the m argument Examples STR 123 456 will return 123 456 STR 123 456 6 will retur
152. romite I O pins to be used for chip or select and touch interrupt respectively any free pins can be used OPTION TOUCH DISABLE PAUSE delay Halt execution of the running program for delay mS This can be a fraction For example 0 2 is equal to 200 uS The maximum delay is 2147483647 mS about 24 days Note that interrupts will be recognised and processed during a pause PIN pin value 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 PIXEL x y c Set a pixel on an attached LCD panel toa colour See the section Basic Drawing Commands for a definition of the colours and graphics coordinates POKE BYTE addr byte or POKE WORD addr word or POKE VAR var offset byte or POKE VARTBL offset byte 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
153. ry The space reserved for saved variables is 1KB These variables can be restored with the VAR RESTORE command which will add all the saved variables to the variable table of the running program Normally this command is placed near the start of a program so that the variables are ready for use by the program This facility is intended for saving data such as calibration data user selected options and other items which changed infrequently It should not be used for high speed saves as you may wear out the flash memory The flash in the Micromite compatible chips has a very high endurance of over 20 000 writes and erases With normal use this will never be reached but it can be exceeded by a program that repeatedly saves variables For example a program that saved a set of variables once a second would wear out the flash in six hours while a program that saved the same data once a day would run for over 50 years and still not wear out the flash If you do want to save data often it would be worth adding a real time clock chip to the Micromite design The RTC SETREG and RTC GETREG commands can then be used to store and retrieve data from the RTC s battery backed memory See the RTC command for more details CPU Speed Control MMBasic provides the ability to control the clock speed of the Micromite via the CPU command The current drawn by the chip is proportional to the clock speed so this command can be used to balance the requirements of performanc
154. s This implementation of the 1 Wire protocol is generally compatible with previous versions with the following differences e The commands are now two words where previously they were one word For example OWWRITE is now ONEWIRE WRITE e You cannot use an array or string variable for data One or more numeric variables are required e The reset command ONEWIRE RESET does not accept a presence variable use the MM ONEWIRE variable instead e The OWSEARCH command and the OWCRC8 and OWCRC16 functions are not implemented The 1 Wire protocol is often used in communicating with the DS18B20 temperature measuring sensor and to help in that regard MMBasic includes the TEMPR function which provides a convenient method of directly reading the temperature of a DS18B20 without using these functions Micromite User Manual Page 88 Appendix D SPI Communications The Serial Peripheral Interface SPI communications protocol is used to send and receive data between integrated circuits The Micromite acts as the master ie it generates the clock UO Pins The SPI OPEN command will automatically configure the relevant I O pins The SPI pinouts are listed at the start of the manual MISO stands for Master In Slave Out and because the Micromite is always the master that pin will be configured as an input Similarly MOSI stands for Master Out Slave In and that pin will be configured as an output When the SPI CLOSE command is used thes
155. 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 Bran
156. s are independent and can be turned on and off and have different frequencies TU or 2 is the controller number and freq is the output frequency between 20 Hz and 500KHz 1A 1B and IC are the duty cycle for each of the Micromite User Manual Page 64 or PWM 2 freq 2A 2B or PWM channel STOP 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 Seed the random number generator with nbr On power up the random number generator is seeded with zero and will generate the same sequence of random numbers each time To generat
157. s now I2C CLOSE Similarly 2CSEN is now I2C SLAVE WRITE etc e Master interrupts are not supported e The NUM2BYTE command and BYTE2NUM function are not implemented use the PEEK function and POKE command instead Micromite User Manual Page 83 Additional CC Ports Additional UC master ports can be added to the Micromite by using the I2CPort embedded C module This is included in the Embedded C Modules folder in the Micromite firmware zip file 7 and 8 Bit Addressing The standard addresses used in these commands are 7 bit addresses without the read write bit MMBasic will add the read write bit and manipulate it accordingly during transfers Some vendors provide 8 bit addresses which include the read write bit You can determine if this is the case because they will provide one address for writing to the slave device and another for reading from the slave In these situations you should only use the top seven bits of the address For example If the read address is 9B hex and the write address is 9A hex then using only the top seven bits will give you an address of 4D hex A simple way of finding the address is to take the 8 bit write address and divide it by 2 Another indicator that a vendor is using 8 bit addresses instead of 7 bit addresses is to check the address range All 7 bit addresses should be in the range of 08 to 77 hex If your slave address is greater than this range then probably your vendor has spec
158. s the full screen editor This will work with any VT100 compatible terminal emulator Tera Term is recommended gt A Tf Input 4 1 lt gt Or Input 4 2 lt gt Then Error Close 1 2 SetPin 16 2 set rx pin as a digital input set tx pin as an output 1 SetPin 18 8 set clk pin high then set it as an outpu SPI open 100000 3 8 A junk SPI 16 17 18 amp H80 M send a command and ignore the_return Junk SPI 16 17 18 get the first byte from the slave junk SPI 16 17 18 get the second byte from the slave SPI close 500000 50 500 25 stop merrrrrrrrrrrer rr err ee eee eee eee eee eee eee eee eee eee eee ee eee eee Print Memory Print Print All tests finished OK JESC Exit__F1 Save F2 Run_F3 Find F4 Mark _F5 Paste Ln 419 Col 1 INS 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
159. 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 For example when the following is run the words Hello World will be printed out DIM MyStr 5 5 MyStr 4 4 Hello MyStr 4 5 World Concat MyStrS PRINT MyStr 0 0 SUB Concat arg arg 0 0 arg 4 4 arg 4 5 END SUB Micromite User Manual Page 44 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 Example of a Defined Function There is often the need for a special command or function to be implemented in MMBasic but in many cases these can be constructed using a defined subroutine or function which will then act exactly the same as a built in command or function For example sometimes there is a requirement for a TRIM function
160. se drivers are located in the CFunctions subdirectory in the firmware distribution zip file See the documentation accompanying the driver for details of how to connect the LCD panel and configure the driver Micromite User Manual Page 20 Touch Support Most ILI9341 based LCD panels are supplied with a resistive touch sensitive panel and associated controller chip To use the touch feature in MMBasic the touch controller must first be connected to the Micromite see the above section for the details and then configured see below Configuring Touch To use the touch facility MMBasic must be configured using the OPTION TOUCH command at the command prompt not in a program This should be done after the LCD panel has been configured see above The syntax is OPTION TOUCH T_CS pin T_IRQ pin Where T_CS pin and T_IRQ pin are the Micromite I O pins to be used for chip select and touch interrupt respectively any free pins can be used This command only needs to be run once as the parameters are stored in non volatile memory Every time the Micromite is restarted MMBasic will automatically initialise the touch controller If the touch facility is no longer required the command OPTION TOUCH DISABLE can be used to disable the touch feature and return the I O pins for general use the T_CS pin should then be wired to 3 3V to disable the controller Calibrating the Touch Screen Before the touch facility can be used it must be calibrated
161. simulated key press and is a number from 0 to 127 The IR signal is modulated at about 38KHz and sending the signal takes about 25mS The CPU speed must be 1OMHz or above KEYPAD var int rl r2 r3 r4 cl c2 c3 c4 or KEYPAD CLOSE Monitor and decode key presses on a 4x3 or 4x4 keypad Monitoring of the keypad is done in the background and the program will continue after this command without interruption var should be a numeric variable and its value will be updated whenever a key press is detected mt is a user defined subroutine that will be called when a new key press is received In the interrupt subroutine the program can examine the variable var and take appropriate action rl r2 r3 and r4 are pin numbers used for the four row connections to the keypad and cl 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 Micromite User Manual Page 58 LET variable expression Assigns the value of ex
162. t font in pixels All characters in a font have the same width Colours Colour is specified as a true colour 24 bit number where the top eight bits represent the intensity of the red colour the middle eight bits the green intensity and the bottom eight bits the blue The easiest way to generate this number is with the RGBQ function which has the form RGB red green blue A value of zero for a colour represents black and 255 represents full intensity The RGBQ function also supports a shortcut where you can specify common colours by naming them For example RGB red or RGB cyan The colours that can be named using the shortcut form are white black blue green cyan red magenta yellow brown and gray MMBasic will automatically translate all colours to the format required by the individual display controller which in the case of the ILI9341 controller is 65K colours in the 565 format The default for commands that require a colour parameter can be set with the COLOUR command This handy if your program uses a consistent colour scheme you can then set the defaults and use the short version of the drawing commands throughout your program The COLOUR command takes the format COLOUR foreground colour background colour Fonts MMBasic includes one built in font which is 8 pixels wide by 13 pixels height and includes all 95 standard ASCII characters Within MMBasic this is referred to as font 1 If required additional f
163. t 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 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 PORT start nbr start nbr Returns the value of a number of I O pins in one operation start is an I O pin number and its value will be returned as bit 0 start 1 will be returned as bit 1 start 2 will be returned as bit 2 and so on for nbr number of bits I O pins used must be numbered consecutively and any I O pin that is invalid or not configured as an input will cause an error The start nbr pair can be repeated if an additional group of input pins need to be added This command can be used to conveniently communicate with parallel devices like memory chips Any number of I O pins and therefore bits can be used from 1 to 23 pins See the PORT command to simultaneously output to a number of pins POS Returns the current cursor position in the line in characters PULSIN pin polarity or PULSIN pin polarity t1 or PULSIN pin polarity t1 t2 Me
164. te the character before the cursor Insert Will switch between insert and overtype mode Escape Key Will close the editor without saving confirms first Fl Save the edited text and exit F2 Save exit and run the program F3 Invoke the search function SHIFT F3 Repeat the search using the text entered with F3 F4 Mark text for cut or copy see below F5 Paste text previously cut or copied When in the mark text mode entered with F4 the editor will allow you to 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 ELSE Introduces a default condition in a multiline IF statement See the multiline IF statement for more details ELSEIF expression THEN Introduces a secondary condition in a multiline IF statement or See the multiline IF statement for more details ELSE IF expression THEN ENDIF Terminates a multiline IF statement or See the multiline IF statement for more details END IF END End the running program and return to the command prompt END FUNCTION Marks the end of a user defined function See the FUNCT
165. th 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 Colour Coded Editor Display The editor has the ability to colour code the edited program with keywords numbers and comments displayed in different colours By default the output is not colour coded but this feature can be enabled with the command OPTION COLOURCODE ON or disabled with OPTION COLOURCODE OFF This setting is saved in flash memory and is automatically applied on startup Note e This feature requires a terminal emulator that can interpret the appropriate escape codes and respond correctly It works correctly with Tera Term however Putty needs its default background colour to be changed to white Settings gt gt Colours gt gt Default Background gt gt Modify e Colour coding the editor s output requires many extra characters to be sent to the terminal emulator and this can slow down the screen update at 38400 baud If colour coding is used it is recommended that the baud rate be set to a higher sp
166. 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 This is described in detail below F5 PASTE This will insert at the current cursor position the text that had been previously cut or copied see below Micromite User Manual Page 33 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
167. tine 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 TEMPR START pin precision This command can be used to start a conversion running on a DS18B20 temperature sensor connected to pin Note that only a single space is allowed between TEMPR and START Normally the TEMPR function alone is sufficient to make a temperature measurement so usage of this command is optional and can be ignored This command will start the measurement on the temperature sensor The program can then attend to other duties while the measurement is running and later use the TEMPR function to get the reading If the TEMPRQ function is used before the conversion time has completed the function will wait for the remaining conversion time before returning the value precision is the resolution of the measurement and is optional It is a number between 0 and 3 meaning Micromite User Manual Page 68 0 0 5 C resolution 100mS conversion time 1 0 25 C resolution 200mS conversion time this is the default 2 0 125 C resolution 400mS conversion time 3 0 0625 C resolution 800mS conversion time TEXT x y string justification font scale c bc Displays a string on an attached LCD panel starting at x and y justification is on
168. trollers 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 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 Micromite User Manual Page 32 Full Screen Editor An important productivity feature of the Micromite i
169. ts Example SELECT CASE nbr CASE 4 9 22 statements IS lt 4 IS gt 88 statements CASE ELSE statements END SELECT 33 TO 88 CASE 5 TO 8 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 Generate a constant stream of positive going pulses for driving a servo The Micromite has two servo controllers with the first being able to control up to three servos and the second two servos Both controllers are independent and can be turned on and off and have different frequencies This command uses the I O pins that are designated as PWM in the diagrams on pages 6 and 7 the two commands are very similar TU or 2 is the controller number freq is the output frequency between 20 Hz and 1000Hz and is optional If not specified it will default to 50Hz 1A 1B and 1C are the pulse widths for each of the controller 1 outputs while 2A and 2B are the pulse widths for the controller 2 outputs The specified TO pins will be automatically configured as outputs while any others will be unaffected and can be used for other duties The pulse width for each output is independent of the others and is specified in milliseconds which can be a fractional number ie 1 536 For accurate positioning the output resolution is about 0 005 mS The minimum value is 0 01mS while
170. uency 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 OPTION COLOURCODE ON _ Turn on or off colour coding for the editor s output Keywords will be in or cyan numbers in red etc The default is off OPTION COLOURCODE Notes OFF e This setting is saved in flash memory and is applied on startup e Colour coding requires a terminal emulator that can interpret the appropriate escape codes It works correctly with Tera Term however Putty needs its default background colour to be changed to white e If colour coding is used it is recommended that the baud rate for the serial console be set to a high speed Micromite User Manual Page 61 OPTION CONSOLE ECHO or OPTION CONSOLE NOECHO or OPTION CONSOLE INVERT or OPTION CONSOLE Used to set options for the console serial port NOECHO will turn off the echoing of characters received at the console ECHO will re enable the echo The default is ECHO at bootup and the option is reset to ECHO whenever the program returns to the command prompt This option is useful when the console is used as a third general purpose serial port INVERT will invert the data polarity on both the console transmit and rece
171. up or reset it will search for this subroutine and if found it will be run once For example if the Micromite has a real time clock attached the library could contain the following code SUB MM STARTUP RTC GETTIME END SUB This would cause the internal clock within MMBasic to be set to the current time on every power up or reset Using MM STARTUP is similar to using the OPTION AUTORUN feature the difference being that the AUTORUN option will cause the whole program in memory to be run from the start where MM STARTUP will just run the code within the subroutine The AUTORUN option and MM STARTUP can be used together and in that case the MM STARTUP subroutine is run first then the program in main memory MM PROMPT If a subroutine with this name exists it will be automatically executed by MMBasic instead of displaying the command prompt This can be used to display a custom prompt set colours define variables etc all of which will be active at the command prompt This subroutine can be located in the library space recommended or in the main program Note that MMBasic will clear all variables and I O pin settings when a program is run so anything set in this subroutine will only be valid for commands typed at the command prompt ie in immediate mode As an example the following will display a custom prompt SUB MM PROMPT PRINT TIMES gt END SUB Note that while constants
172. upply the controller draws less than 10mA Micromite User Manual Page 19 Where a Micromite connection is listed as configurable the specific pin should be specified with the OPTION LCDPANEL or OPTION TOUCH commands see below The backlight power the LED connection should be supplied from the main 5V supply via a current limiting resistor A typical value for this resistor is 18Q which will result ina LED current of about 63mA The value of this resistor can be varied to reduce the power consumption or to provide a brighter display Important Care must be taken with display panels that share the SPI port between a number of devices display controller touch etc In this case all the Chip Select signals must be configured in MMBasic or disabled by a permanent connection to 3 3V If this is not done any unconnected Chip Select pins will float causing the wrong controller to respond to commands on the SPI bus Configuring MMBasic To use the display MMBasic must be configured using the OPTION LCDPANEL command which must be entered at the command prompt not in a program The syntax is OPTION LCDPANEL ILI9341 orientation D C pin reset pin CS pin Where orientation can be LANDSCAPE PORTRAIT RLANDSCAPE or RPORTRAIT These can be abbreviated to L P RL or RP The R prefix indicates the reverse or upside down orientation C D pin and reset pin are the Micromite I O pins to be used for these functi
173. ured state Then can then be configured using SETPIN This command will also send a stop if the bus is still held Micromite User Manual Page 82 And similarly there are four commands for the slave mode I2C SLAVE OPEN addr Enables the UC module in slave mode mask option send_int addr is the slave PC address DX mask is the address mask normally 0 bits set as 1 will always match This allows the slave to respond to multiple addresses option is a number between 0 and 3 normally this is set to 0 1 allows MMBasic to respond to the general call address When this occurs the value of MM DC will be set to 4 2 treat the address as a 10 bit address 3 combine and 2 send mt is the subroutine to be invoked when the module has detected that the master is expecting data rcv_int is the subroutine to be called when the module has received data from the master Note that this is triggered on the first byte received so your program might need to wait until all the data is received I2C SLAVE WRITE Send the data to the UC master This command should be used in the send sendlen senddata sendata interrupt ie in the send mt subroutine when the master has requested data Alternatively a flag can be set in the interrupt subroutine 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
174. using the GUI CALIBRATE command This command will present a target in the top left corner of the screen Using a pointed object such as a stylus press exactly on the centre of the target and hold the stylus down for at least a second MMBasic will record this location and then continue the calibration by sequentially displaying the target in the other three corners of the screen for touch and calibration The calibration routine may warn that the calibration was not accurate This is just a warning and you can still use the touch feature if you wish but it would be better to repeat the calibration using more care Following calibration you can test the touch facility using the GUI TEST TOUCH command This command will blank the screen and wait for a touch When the screen is touched a white dot will be placed on the display marking the position on the screen If the calibration was carried out successfully the dot should be displayed exactly under the location of the stylus on the screen To exit the test routine you can press any key on the console s keyboard Touch Functions To detect if and where the screen is touched you can use the following functions in a BASIC program O TOUCH X Returns the X coordinate of the currently touched location TOUCH Y Returns the Y coordinate of the currently touched location Both functions return 1 if the screen is not being touched Touch Interrupts An interrupt can be set on th
175. verter 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 Tera Term Serial port su Ze Port Baud rate Data Parity Stop Flow control Transmit delay 0 msecjchar 0 msecjline 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 iicromite MMBasic Ver 4 5 opyright 2011 2014 Geoff Graham gt E Micromite User Manual Page 10 A Simple Program Assuming that you have correctly connected a term
176. would be different For example the following was accepted and also led to obscure bugs Nbr 123 Nbr abcd In version 4 6 and later of MMBasic this is illegal If you try to use Nbr an error would be raised stating that the variable has already been defined with a different type ie floating point Most programs use floating point variables as these can deal with the numbers used in typical situations and are more intuitive when dealing with division and fractions So if you are not bothered with the details always use floating point When a constant number is used it will be assumed that it is an integer if a decimal point or exponent is not used For example 1234 will be interpreted as an integer and 1234 0 will be interpreted as a floating point number String constants are always surrounded by double quote marks eg text string 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
177. y 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 lt type gt 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 argl 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 User Manual Page 42 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

Download Pdf Manuals

image

Related Search

Related Contents

作業環境改善に寄与する印刷産業機械に関する調査研究報告書  MANUAL DE INSTALAÇÃO - Ministério da Previdência Social  AQUALAND GRAPH Ver.2  Beko CSG 62010 DW cooker  Manuel d`utilisation    Phoenix Gold Speaker ATCLCR6 User's Manual  Océ TDS320 User Manual - Océ  Sony Ericsson Mobile Communications AB  AML M7220 User Manual  

Copyright © All rights reserved.
Failed to retrieve file