Commands
Commands Detailed Listing 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.
*file
The star/asterisk command is a shortcut for RUN that may only be used at the MMBasic prompt. eg,
RUN *foo RUN "foo" *"foo bar" RUN "foo bar" *foo –wombat RUN "foo", "--wombat" *foo "wom" RUN "foo", CHR$(34) + "wom" + CHR$(34) *foo --wom="bat" RUN "foo","--wom=" + CHR$(34) + "bat" + CHR$(34) String expressions are not supported/evaluated by this command; any arguments provided are passed as a literal string to the RUN command.
? (question mark)
Shortcut for the PRINT command.
/* */
Start and end of multiline comments. /* and */ must be the first non-space characters at the start of a line and have a space or end-of-line after them (i.e. they are MMBasic commands). Multi-line comments cannot be used inside subroutines and functions. Any characters after */ on a line are also treated as a comment.
.PROGRAM name .END PROGRAM [list] .SIDE SET n .LABEL label .LINE n or NEXT .WRAP n .WRAP TARGET n JMP params WAIT params IN params OUT params PUSH params PULL params MOV params NOP params IRQ SET params IRQ WAIT params IRQ CLEAR params IRQ NOWAIT params IRQ params SET params
Commands for writing in-line PIO assembler programs. In all cases the parameters are unquoted string literals. Variables are not allowed.
A: or B:
Shortcut for DRIVE “A:” and DRIVE “B:” at the command prompt
PicoMite User Manual
Page 99
ADC
The ADC commands provide an alternate method of recording analog inputs and are intended for high speed recording of many readings into an array.
ADC OPEN freq, n_channels [,interrupt]
This allocates up to 4 ADC channels for use and sets them to be converted at the specified frequency. The range of pins are GP26, GP27, GP28, and GP29 for the RP2940 and RP2350A. Plus GP55, GP56, GP57, GP58 on the RP2350B. If the number of channels is one then it will always be GP26 used, if two then GP26 and GP27 are used, etc. Sampling of multiple channels is sequential (there is only one ADC). The pins are locked to the function when ADC OPEN is active The maximum total frequency is CPUspeed/96 (eg, 520KHz if all four channels are to be sampled with the CPU set at 200MHz). Note that a aggregate sampling frequency over 500Khz is overclocking the ADC. The optional interrupt parameter specifies an interrupt to call when the conversion completes. If not specified then conversion will be blocking
ADC FREQUENCY freq
This changes the sampling frequency of the ADC conversion without having to close and re-open
ADC CLOSE
Releases the pins to normal usage
ADC START array1!() [,array2!()] [,array3!()] [,array4!()] [,C1min] [,C1max] [,C2min] [,C2max] [,C3min] [,C3max] [,C4min] [,C4max]
This starts conversion into the specified arrays. The arrays must be floating point and the same size. The size of the arrays defines the number of conversions. Start can be called repeatedly once the ADC is OPEN ‘Cxmin’ and ‘Cxmax’ will scale the readings. For example, C1min=200 and C1max=100 will create values ranging from 200 to 100 for equivalent voltages of 0 - 3.3. If the scaling is not used the results are returned as a voltage between 0 and OPTION VCC (defaults to 3.3V).
ADC RUN array1%(),array2%)
Runs the ADC continuously in double buffered mode. The ADC first fills array1% and then array2% and then back to array1% etc. If more than one ADC channel is specified in the ADC OPEN command the data are interleaved. The data is returned as packed 8-bit values (Use MEMORY UNPACK to convert to a normal array). MM.INFO(ADC) will return the number of the buffer currently available for reading (1 or 2).
ARRAY ADD in(), value ,out()
This adds (or appends for strings) the value 'value' to every element of the matrix in() and puts the answer in out(). Works for arrays of any dimensionality of strings and both integer and float (can convert between integer and float). Setting num to 0 or “” is optimised and is a fast way of copying an entire array. in() and out() can be the same array.
ARRAY INSERT targetarray(), [d1] [,d2] [,d3] [,d4] [,d5] , sourcearray()
This is the opposite of ARRAY SLICE, has a very similar syntax, and allows you, for example, to substitute a single vector into an array of vectors with a single instruction or a one dimensional array of strings into a two dimensional array of strings. The arrays can be numerical or strings and ‘sourcearray’ and ‘destinationarray’ must be the same (NB: can convert between integers and floats for numerical arrays). eg, OPTION BASE 1 DIM targetarray(3,4,5) DIM sourcearray(4)=(1,2,3,4) ARRAY INSERT targetarray(), 2, , 3, sourcearray() Will set elements 2,1,3 = 1 and 2,2,3 = 2 and 2,3,3 = 3 and 2,4,3 = 4
Page 100
PicoMite User Manual
ARRAY SET value, array()
Sets all elements in array() to the value ‘value’. Value can be a number or a string and ‘array’ must be the same (NB: can convert between integers and floats). Note this is the fastest way of clearing an array by setting it to zero or an empty string.
ARRAY SLICE sourcearray(), [d1] [,d2] [,d3] [,d4] [,d5] destinationarray()
This command copies a specified set of values from a multi-dimensional array into a single dimensional array. It is much faster than using a FOR loop. The slice is specified by giving a value for all but one of the source array indices and there should be as many indices in the command, including the blank one, as there are dimensions in the source array. The arrays can be numerical or strings and ‘sourcearray’ and ‘destinationarray’ must be the same (NB: can convert between integers and floats for numerical arrays). eg, OPTION BASE 1 DIM a(3,4,5) DIM b(4) ARRAY SLICE a(), 2, , 3, b() Will copy the elements 2,1,3 and 2,2,3 and 2,3,3 and 2,4,3 into array b()
ARC x, y, r1, [r2], a1, a2 [, c]
Draws an arc of a circle with a given colour and width between two radials (defined in degrees). Parameters for the ARC command are: x: X coordinate of centre of arc y: Y coordinate of centre of arc r1: inner radius of arc r2: outer radius of arc - can be omitted if 1 pixel wide a1: start angle of arc in degrees a2: end angle of arc in degrees c: Colour of arc (if omitted it will default to the foreground colour) Zero degrees is at the 12 o'clock position.
AUTOSAVE or AUTOSAVE CRUNCH or AUTOSAVE APPEND
Enter automatic program entry mode. This command will take lines of text from the console serial input and save them to program memory. This mode is terminated by entering Control-Z or F1 which will then cause the received data to be transferred into program memory overwriting the previous program. Use F2 to exit and immediately run the program. The CRUNCH option instructs MMBasic to remove all comments, blank lines and unnecessary spaces from the program before saving. This can be used on large programs to allow them to fit into limited memory. CRUNCH can be abbreviated to the single letter C. The APPEND option will leave the existing program intact and append the new data from the serial input to the end of it. 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 Raspberry Pi Pico. 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.
BACKLIGHT n [,DEFAULT] BACKLIGHT n [,FreqInHz]
PicoMite User Manual
NON VGA OR HDMI VERSIONS Sets the display backlight, valid values are 0 to 100. If DEFAULT is specified then the firmware will automatically set the backlight to that level on powerup. This is particularly useful for battery operation where reducing the backlight level can significantly increase battery life. Some circuits are too slow to use the default backlight PWM frequency which is chosen to avoid interference with audio. In which case a user frequency can be specified. This is a temporary option and will need setting on reboot.
Page 101
BIT(var%, bitno) = value
Sets a specific bit (0-63) in an integer variable. ‘value’ can be 0 or 1. See also the BIT function
BITBANG
Replaced by the command DEVICE. For compatibility BITBANG can still be used in programs and will be automatically converted to DEVICE
BLIT
BLIT is a simple memory operation copying to and from a display or memory to a display or memory. Notes: 32 buffers are available ranging from #1 to #32. When specifying the buffer number the # symbol is optional. All other arguments are in pixels.
BLIT READ [#]b, x, y, w, h
BLIT READ will copy a portion of the display to the memory buffer '#b'. The source coordinate is 'x' and 'y' and the width of the display area to copy is 'w' and the height is 'h'. When this command is used the memory buffer is automatically created and sufficient memory allocated. This buffer can be freed and the memory recovered with the BLIT CLOSE command.
BLIT WRITE [#]b, x, y [,mode]
BLIT WRITE will copy the memory buffer '#b' to the display. The destination coordinate is 'x' and 'y'. The optional 'mode' parameter defaults to 0 and specifies how the stored image data is changed as it is written out. It is the bitwise AND of the following values: &B001 = mirrored left to right &B010 = mirrored top to bottom &B100 = don't copy transparent pixels
BLIT LOAD[BMP] [#]b, fname$ [,x] [,y] [,w] [,h]
BLIT LOAD will load a blit buffer from a 24-bit bmp image file. x,y define the start position in the image to start loading and w,h specify the width and height of the area to be loaded. This command will work on most display panels (not just panels using the ILI9341 controller). eg, BLIT LOAD #1,"image1", 50,50,100,100 will load an area of 100 pixels square with the top left had corner at 50,50 from the image image1.bmp
BLIT CLOSE [#]b
BLIT CLOSE will close the memory buffer '#b' to allow it to be used for another BLIT READ operation and recover the memory used.
BLIT MERGE colour, x, y, w, h
BLIT FRAMEBUFFER from, to, xin, yin, xout, yout, width, height [,colour]
Page 102
NOT VGA OR HDMI VERSIONS Copies an area of the framebuffer defined by the ‘x’ and ‘y’ pixel coordinates of the top left and with a width of ‘w’ and height ‘h’ to the LCD display. As part of the copy it will overlay the LCD display with pixels from the layer buffer that aren’t set to the ‘colour’ specified. The colour is specified as a number between 0 and 15 representing: Black, Blue, Myrtle, Cobalt, Midgreen, Cerulean, green, cyan, red, magenta, rust, fuschia, brown, lilac, yellow and white Requires both a framebuffer and a layer buffer to have been created to operate. Will automatically wait for frame blanking before starting the copy on ILI9341, ST7789_320 and ILI9488 displays Copies an area of a specific ‘from’ framebuffer N, F, or L to another different ‘to’ framebuffer N, F, or L. ‘xin’ and ‘yin’ define the top left of the area of ‘width’ and ‘height’ on the source framebuffer to be copied. ‘xout’ and ‘yout’ define the top left of the area on the target framebuffer to receive the copy. The optional parameter colour defines a pixel colour on the source which will not be copied. If omitted all pixels are copied. The colour is specified as a number between 0 and 15 representing: Black, Blue, Myrtle, Cobalt, Midgreen, Cerulean, green, cyan, red, magenta, rust, fuschia, brown, lilac, yellow and white
PicoMite User Manual
Requires both a framebuffer and a layer buffer to have been created to operate. Will automatically wait for frame blanking before starting the copy on ILI9341, ST7789_320 and ILI9488 displays BLIT MEMORY address, x, y [,col]
Copies an area of memory treated as a packed array of colour nibbles to the current graphical output as specified by FRAMEBUFFER WRITE. The colour is specified as a number between 0 and 15 representing: Black, Blue, Myrtle, Cobalt, Midgreen, Cerulean, green, cyan, red, magenta, rust, fuschia, brown, lilac, yellow and white The first word of the area of memory starting at ‘address%’ must contain the width and height of the area to be copied as 16-bit integers with the width as the bottom 16 bits. The address must be aligned to a word boundary (divisible by 4). If the optional parameter ‘col’ is specified then that specific colour is not copied. If the top bit of either the width or height is set to 1 then the colour data is treated as compressed (the remaining 15 bits are used as the width and/or height). The compression algorithm is simple, each byte contains a count in the bottom nibble (1-15) and a colour in the top nibble (0-15). In the event that more than 15 pixels are the same colour additional bytes are used for that colour.
BLIT COMPRESSED address%, x, y [,col]
Acts the same as BLIT MEMORY but assumes the data is compressed and ignores the top bit in the width and height
BLIT x1, y1, x2, y2, w, h
Copy one section of the display screen to another part of the display. The source coordinate is 'x1' and 'y1'. The destination coordinate is 'x2' and 'y2'. The width of the screen area to copy is 'w' and the height is 'h'. All arguments are in pixels. If the output is to an LCD panel it must be either the SSD19863, ILI9341_8, ILI9341, ILI9488 (if MISO connected), or ST7789_320 controllers.
BOX x, y, w, h [, lw] [,c] [,fill]
Draws a box on the display with the top left hand corner at 'x' and 'y' with a width of 'w' pixels and a height of 'h' pixels. '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 fill colour. It can be omitted or set to -1 in which case the box will not be filled. All parameters can be expressed as arrays and the software will plot the number of boxes as determined by the dimensions of the smallest array. 'x' and 'y', must both be arrays or be single variables /constants otherwise an error will be generated. 'w', 'h' , 'lw', 'c', and fill can be either arrays or single variables/constants. See the chapter Graphics Commands and Functions for a definition of the colours and graphics coordinates
BYTE(var$, byteno)=value
Sets a specific byte in a string to an integer value. ‘value’ can be in the range 0255. The byteno can be between 1 and the current length of the string variable. This is the equivalent of MID$(var$,byteno,1)=CHR$(value) but executes much faster. See also the BYTE function.
CALL usersubname$ [,usersubparameters,..]
This is an efficient way of programmatically calling user defined subroutines (see also the CALL() function). In many cases it can allow you to get rid of complex SELECT and IF THEN ELSEIF ENDIF clauses and is processed in a much more efficient way.
PicoMite User Manual
Page 103
The “usersubname$” can be any string or variable or function that resolves to the name of a normal user subroutine (not an in-built command). The “usersubparameters” are the same parameters that would be used to call the subroutine directly. A typical use could be writing any sort of emulator where one of a large number of subroutines should be called depending on some variable. It also allows a way of passing a subroutine name to another subroutine or function as a variable.
CAMERA
NOT VGA OR HDMI Command supporting the OV7670 camera module.
CAMERA OPEN XLKpin, PLKpin, HSpin, VSCpin, RETpin, D0pin
This initialises the camera, It outputs a 12MHz clock on XLK (PWM) and checks that it is correctly receiving signals on PLK, VS, and HS. The camera is set to a resolution of 160x120 (QQVGA) which is the maximum achievable within the limits of the available memory. Enable OPTION SYSTEM I2C in the PicoMite firmware and wire SCL and SDA to the relevant pins (may be labelled SIOC and SIOD on the camera module). These connections must have a pullup to 3.3V - 2K7 recommended) Other pins are wired as per the OPEN command. (NB: VS may be labelled VSYNC, HS may be labelled HREF, PLK may be labelled PCLK, RET may be labelled RESET and XLK may be XCLK on your module) D0pin defines the start of a range of 8 contiguous pins (eg,GP0 - GP7).
CAMERA CAPTURE [scale, [x , y]]
This captures a picture from the camera (RGB565) and displays it on an LCD screen. An SPI LCD must be connected and enabled in order for the command to work. (ILI9341 and ST7789_320 recommended). Scale defaults to 1 and x,y each to 0 By default a 160x120 image is output on the LCD with the top left at 0,0 on the LCD. Setting scale to 2 will fill a 320x240 display with the image. Setting the x and y parameters will offset the top left of the image on the LCD. Update rate in a continuous loop is 7FPS onto the display at 1:1 scale and 5FPS scaled to 320x240. Assuming the display has MISO wired it is then possible to save the image to disk using the SAVE IMAGE command.
CAMERA CLOSE
Closes the camera subsystem and frees up all the pins allocated in the OPEN command.
CAMERA CHANGE image%(),change! [,scale [,x ,y]]
The camera firmware is also able to detect motion in the camera's field of view using the command. It does this by operating the camera in YUV mode rather than RGB. This has the advantage that the intensity information and colour information are separated and just one byte is needed for a 256-level greyscale image which is ideal fer detecting movement. image% is an array of size 160x120 bytes (DIM image%(160,120/8-1) On calling the command it holds a packed 8-bit greyscale image. The change! variable returns the percentage the image has changed from the previous time the command was called. Optionally if "scale" is set then the image delta is output to the screen i.e. the difference between the previous image and this one. As in the CAPTURE command the delta image can be scaled and positioned as required. If the scale parameter is omitted then the LCD is not updated by this command.
CAMERA TEST tnum
Enables or disables a test signal from the camera. tnum=2 generates colourbars and tnum=0 sets back to the visual input.
Page 104
PicoMite User Manual
CAMERA REGISTER reg%, data%
Sets the register "reg%" in the camera to the value "data%". When used the command will report to the console the previous value and automatically confirms that the new value has been set as requested. The colour rendition of the camera as initialised is reasonable but could probably be improved further by tuning the various camera registers.
CAT S$, N$
Concatenates the strings by appending N$ to S$. This functionally the same as S$ = S$ + N$ but operates somewhat faster.
CHAIN fname$ [cmdline$]
Allows a program to run another program with the variable space preserved – the command is recommended to be used in top level program and not from within a subroutine. If the optional ‘cmdline$ parameter is specified this is passed to the chained program in MM.CMDLINE$
CHDIR dir$
Change the current working directory on the default drive to ‘dir$’ The special entry “.” represents the parent of the current directory and “.” represents the current directory. "/" is the root directory.
CIRCLE x, y, r [,lw] [, a] [, c] [, fill]
Draw a circle centred at 'x' and 'y' with a radius of 'r' on the display output. ‘lw’ is optional and is the line width (defaults to 1). '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 and can be omitted or set to -1 in which case the box will not be filled. All parameters can be expressed as arrays and the software will plot the number of circles as determined by the dimensions of the smallest array. 'x', 'y' and 'r' must all be arrays or all be single variables/constants otherwise an error will be generated. 'lw', 'a', 'c', and fill can be either arrays or single variables/constants. See the chapter Graphics Commands and Functions for a definition of the colours and graphics coordinates.
CLEAR
Delete all variables and recover the memory used by them. See ERASE for deleting specific array variables.
CLOSE [#]fnbr [,[#]fnbr] …
Close the file(s) previously opened with the file number ‘#fnbr’. The # is optional. Also see the OPEN command.
CLS [colour]
Clears the LCD panel's screen. Optionally 'colour' can be specified which will be used for the background colour when clearing the screen.
CMM2 LOAD or CMM2 RUN
Loads and or runs a program from disk using the CMM2 program loading mechanism. This includes an aggressive crunching of the program and supports #INCLUDE files and #DEFINE text replacement. This can be used for compatibility with CMM2 programs or to allow structuring programs into separate modules. It is important to note that if used all editing of programs must be offline or direct to and from disk as the source files cannot be reconstructed from the version loaded by these commands.
COLOUR fore [, back] or COLOR fore [, back]
Sets the default colour for commands (PRINT, etc) that display on the on the attached LCD panel. 'fore' is the foreground colour, 'back' is the background colour. The background is optional and if not specified will default to black.
COLOUR MAP inarray%(), outarray%() [,colourmap%()]
This command generates RGB888 colours in outarray% from colour codes (015) in inarray%. If the optional colourmap% parameter is used this must be 16 elements long). In this case the values in inarray% are mapped to the colours for that index value in colourmap%
PicoMite User Manual
Page 105
CONFIGURE cfg
Configures a board as per the “cfg” specified equivalent of OPTION RESET).
CONFIGURE LIST
Lists all the various configurations available for the firmware version.
CONST id = expression [, id = expression] … etc
Create a constant identifier which cannot be changed once created. 'id' 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.
CONTINUE
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. Note that it is not always possible to resume the program correctly – this particularly applies to complex programs with graphics, nested loops and/or nested subroutines and functions.
CONTINUE DO or CONTINUE FOR
Skip to the end of a DO/LOOP or a FOR/NEXT loop. The loop condition will then be tested and if still valid the loop will continue with the next iteration.
COPY fname1$ TO fname2$
Copy a file from ‘fname1$’ to ‘fname2$’. Both are strings. A directory path can be used in both 'fname$' and 'fname$'. If the paths differ the file specified in 'fname$' will be copied to the path specified in 'fname2$' with the file name as specified. The filenames can include the drive specification in the case that you are copying to and or from the non-active drive (see the DRIVE command) Wildcard copy. The bulk copy is triggered if fname$ contains a '*' or a '?' character. dirname$ must be a valid directory name and should NOT end in a slash character
COPY fname$ TO dirname$
CPU RESTART
Will force a restart of the processors. This will clear all variables and reset everything (eg, timers, COM ports, I2C, etc) similar to a power up situation but without the power up banner. If OPTION AUTORUN has been set the program in the specified flash location or program memory will restart.
CPU SLEEP n
Will cause the processors to sleep for ‘n’ seconds. Note that the CPU does not have a true low power sleep so the power saving is limited.
CSUB name [type [, type] …] hex [[ hex[…] hex [[ hex[…] END CSUB
Defines the binary code for an embedded machine code program module written in C or ARM assembler. The module will appear in MMBasic as the command 'name' and can be used in the same manner as a built-in command. Multiple embedded routines can be used in a program with each defining a different module with a different 'name'. The first 'hex' word is a 32 bit word which is the offset in bytes from the start of the CSUB to the entry point of the embedded routine (usually the function main()). The following hex words are the compiled binary code for the module. These are automatically programmed into MMBasic when the program is saved. Each 'hex' must be exactly eight hex digits representing the bits in a 32-bit word and be separated by one or more spaces or new lines. The
Page 106
PicoMite User Manual
command must be terminated by a matching END CSUB. Any errors in the data format will be reported when the program is run. During execution MMBasic will skip over any CSUB commands so they can be placed anywhere in the program. The type of each parameter can be specified in the definition. For example: CSUB MySub integer, integer, string This specifies that there will be three parameters, the first two being integers and the third a string. Note: Up to ten arguments can be specified ('arg1', 'arg2', etc). If a variable or array is specified as an 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. In the case of arrays, they should be passed with empty brackets eg, arg(). In the CSUB the argument will be supplied as a pointer to the first element of the array. Constants and expressions will be passed to the embedded C routine as pointers to a temporary memory space holding the value. 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[YY]" or DATE$ = "DD/MM/YY[YY]" or DATE$ =”YYYY-MM-DD” or DATE$=”YYYY/MM/DD”
Set the date of the internal clock/calendar. DD, MM and YY are numbers, for example: DATE$ = "28-7-2014" With OPTION RTC AUTO ENABLE the PicoMite firmware starts with the DATE$ programmed in RTC. Without OPTION RTC AUTO ENABLE the PicoMite firmware starts with the date set to "01-01-2024" on power up.
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 (i.e. selected using the FONT command or specified in the TEXT command). See the Embedded Fonts folder in the PicoMite firmware distribution zip file for a selection of embedded fonts and a full description of how to create them. '#Nbr' is the font's reference number (from 1 to 16). It can be the 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. Multiple lines of 'hex' words can be used with the command terminated by a matching END DEFINEFONT. Multiple embedded fonts can be used in a program with each defining a different font with a different font number. During execution MMBasic will skip over any DEFINEFONT commands so they can be placed anywhere in the program. Any errors in the data format will be reported when the program is saved.
PicoMite User Manual
Page 107
DEVICE BITSTREAM pinno, n_transitions, array%()
This command is used to generate an extremely accurate bit sequence on the pin specified. The pin must have previously been set up as an output and set to the required starting level. Notes: The array contains the length of each level in the bitstream in microseconds. The maximum period allowed is 65.5 mSec The first transition will occur immediately on executing the command. The last period in the array is ignored other than defining the time before control returns to the program or command line. The pin is left in the starting state if the number of transitions is even and the opposite state if the number of transitions is odd.
DEVICE CAMERA
See CAMERA command
DEVICE GAMEPAD
See GAMEPAD command
DEVICE HUMID
See HUMID command
DEVICE KEYPAD
See KEYPAD command
DEVICE MOUSE
See MOUSE command
DEVICE LCD
See LCD command
DEVICE SERIALTX pinno, baudrate, ostring$
Outputs 'ostring$' as a serial data stream on 'pinno'. 'baudrate' can be between 110 and 230400 (230400 may need CPU to be overclocked). Note that the program will halt and interrupts ignored during transmission.
DEVICE SERIALRX pinno, baudrate, istring$, timeout_in_ms, status% [,nbr] [,terminators$]
Inputs serial data on ‘pinno’. ‘baudrate’ can be between 110 and 230400 (230400 may need CPU to be overclocked). ‘status%’ returns: -1 = timeout (Note: use LEN(istring$) to see number of chars received) 2 = number of characters requested satisfied 3 = terminating character satisfied ‘nbr’ specifies the number of characters to be received before the command returns. ‘terminators$’ specifies one or more signle characters that can be used to terminate reception. The program will halt and interrupts ignored while this command is executing.
DEVICE WII
See WII command
DEVICE WS2812
See WS2812 command
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 FLOAT or INTEGER or STRING (the type can be prefixed by the keyword AS - as in AS FLOAT)
Declares one or more variables (i.e. makes the variable name and its characteristics known to the interpreter). When OPTION EXPLICIT is used (as recommended) the DIM, LOCAL or STATIC 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 (i.e. string, float or integer) can be specified in one of three ways: By using a type suffix (i.e. !, % or $ for float, integer or string). For example: DIM nbr%, amount!, name$ By using one of the keywords FLOAT, INTEGER or STRING immediately after the command DIM and before the variable(s) are listed. The specified
Page 108
PicoMite User Manual
'init' is the value to initialise
the variable and consists of:
=
Examples: DIM nbr(50) DIM INTEGER nbr(50) DIM name AS STRING DIM a, b$, nbr(100), strn$(20) DIM a(5,5,5), b(1000) DIM strn$(200) LENGTH 20 DIM STRING strn(200) LENGTH 20 DIM a = 1234, b = 345 DIM STRING strn = "text" DIM x%(3) = (11, 22, 33, 44)
type then applies to all variables listed (i.e. it does not have to be repeated). For example: DIM STRING first_name, last_name, city By using the Microsoft convention of using the keyword "AS" and the type keyword (i.e. FLOAT, INTEGER or STRING) after each variable. If you use this method the type must be specified for each variable and can be changed from variable to variable. For example: DIM amount AS FLOAT, name AS STRING Floating point or integer variables will be set to zero when created and strings will be set to an empty string (i.e. ""). You can initialise the value of the variable by using an equals symbol (=) and an expression following the variable definition. For example: DIM STRING city = "Perth", house = "Brick" The initialising value can be an expression (including other variables) and will be evaluated when the DIM command is executed. See the chapter Defining and Using Variables for more examples of the syntax. As well as declaring simple variables the DIM command will also declare arrayed variables (i.e. an indexed variable with a number of dimensions). Following the variable's name the dimensions are specified by a list of numbers separated by commas and enclosed in brackets. For example: DIM array(10, 20) Each number specifies the index range in each dimension. Normally the indexing of each dimension starts at 0 but the OPTION BASE command can be used to change this to 1. The above example specifies a two dimensional array with 11 elements (0 to 10) in the first dimension and 21 (0 to 20) in the second dimension. The total number of elements is 231 and because each floating point number requires 8 bytes a total of 1848 bytes of memory will be allocated. Strings will default to allocating 255 bytes (i.e. characters) of memory for each element and this can quickly use up memory when defining arrays of strings. 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 STRING s(5, 10) will declare a string array with 66 elements consuming 16,896 bytes of memory while: DIM STRING s(5, 10) LENGTH 20 Will only consume 1,386 bytes of memory. Note that the amount of memory allocated for each element is n + 1 as the extra byte is used to track the actual length of the string stored in each element. If a string longer than 'n' is assigned to an element of the array an error will be produced. Other than this, string arrays created with the LENGTH keyword act exactly the same as other string arrays. This keyword can also be used with non-array string variables but it will not save any memory. In the above example you can also use the Microsoft syntax of specifying the type after the length qualifier. For example: DIM s(5, 10) LENGTH 20 AS STRING Arrays can also be initialised when they are declared by adding an equals symbol (=) followed by a bracketed list of values at the end of the declaration. For example: DIM INTEGER nbr(4) = (22, 44, 55, 66, 88) or DIM s$(3) = ("foo", "boo", "doo", "zoo")
PicoMite User Manual
Page 109
Note that the number of initialising values must match the number of elements
in the array including the base value set by OPTION BASE. If a multi
dimensioned array is initialised then the first dimension will be initialised first
followed by the second, etc.
Also note that the initialising values must be after the LENGTH qualifier (if
used) and after the type declaration (if used).
DO
This structure will loop forever; the EXIT DO command can be used to terminate the loop or control must be explicitly transferred outside of the loop by commands like GOTO or EXIT SUB (if in a subroutine).
DO WHILE expression
Loops while ‘expression’ is true (this is equivalent to the older WHILE-WEND loop). If, at the start, the expression is false the statements in the loop will not be executed, not even once.
DO
Loops until the expression following UNTIL is true. Because the test is made at the end of the loop the statements inside the loop will be executed at least once, even if the expression is true.
DO
Loops until the expression following WHILE is false. Because the test is made at the end of the loop the statements inside the loop will be executed at least once, even if the expression is false.
DRAW3D
NOT AVAILABLE ON THE WEBMITE VERSION The 3D engine includes commands for manipulating 3D images including setting the camera, creating, hiding, rotating, etc. See the document “The CMM2 3D engine.pdf” in the PicoMite firmware download for a full description.
DRIVE drive$
Sets the active disk drive as ‘drive$’. ‘drive$’ can be “A:” or “B:” where A is the flash drive and B is the SD Card if configured
EDIT or EDIT fname$ or EDIT FILE fname$
Invoke the full screen editor. If a filename is specified the editor will load the file from the current disk (A: or B:) to allow editing and on exit with F1 or F2 save it to the disk. If the file does not exist it is created on exit. The current program stored in flash memory is not affected. If editing an existing file a backup with .bak appended to the filename is also created on exit. If fname$ includes an extension other than .bas then colour coding will be temporarily turned off during the edit. If no extension is specified the firmware will assume .bas Editing a file from disk allows non-Basic files such as html or sprite files to be edited without corruption during the tokenising process that happens when stored to flash. EDIT and EDIT fname$ can only be invoked at the command prompt. If you wish to edit a file in a program you can use the EDIT FILE fname$ command. The command must be used in the top level program and not from within a subroutine. EDIT FILE fname$ differs from EDIT fname$ in that it will automatically save the entire variable space to the A: drive and restores it on exit. The command will fail if there is not enough free space on the A: drive. In the case of an RP2350 with PSRAM the variable space will be saved to a reserved area in the PSRAM and the A: drive is not used. See the chapter Full Screen Editor for details of how to use the editor.
ELSE
Introduces an optional default condition in a multiline IF statement. See the multiline IF statement for more details.
Page 110
PicoMite User Manual
ELSEIF expression THEN or ELSE IF expression THEN
Introduces an optional secondary condition in a multiline IF statement. See the multiline IF statement for more details.
END [noend] or END cmd$
End the running program and return to the command prompt. If a subroutine named MM.END exists in the program it will be executed whenever the program ends with an actual or implied END command. It is not executed if the program ends with the break character (ie, Ctrl-C). The optional parameter ‘noend’ can be used to block execution of the MM.END subroutine eg, “END noend” if 'cmd$' is specified then it will be executed as though at the command prompt after the program finishes. Note: if "END cmd$" is used but a subroutine MM.END exists it will be executed and cmd$ ignored.
END CSUB
Marks the end of a C subroutine. See the CSUB command. Each CSUB must have one and only one matching END CSUB statement.
END FUNCTION
Marks the end of a user defined function. See the FUNCTION command. Each function must have one and only one matching END FUNCTION statement. Use EXIT FUNCTION if you need to return from a function from within its body.
ENDIF or END IF
Terminates a multiline IF statement. See the multiline IF statement for more details.
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 global variables and frees up the memory allocated to them. This will work with arrayed variables and normal (non array) variables. Arrays can be specified using empty brackets (eg, dat()) or just by specifying the variable's name (eg, dat). Use CLEAR to delete all variables at the same time (including arrays).
ERROR [error_msg$]
Forces an error and terminates the program. This is normally used in debugging or to trap events that should not occur. 'error_msg$' is optional and is the message to display on the console.
EXECUTE command$
This executes the Basic command "command$". Use should be limited to basic commands that execute sequentially for example the GOTO statement will not work properly Things that are tested and work OK include GOSUB, Subroutine calls, other simple statements (like PRINT and simple assignments) Multiple statements separated by : are not allowed and will error The command sets an internal watchdog before executing the requested command and if control does not return to the command, like in a GOTO statement, the timer will expire. In this case you will get the message "Command timeout". RUN is a special case and will cancel the timer allowing you to use the command to chain programs if required.
PicoMite User Manual
Page 111
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.
FILES [fspec$] [,sort]
Lists files in any directories on the default Flash Filesystem or SD Card. 'fspec$' (if specified) can contain a path and search wildcards in the filename. Question marks (?) will match any character and an asterisk (*) will match any number of characters. If omitted, all files will be listed. For example:
- Find all entries .TXT Find all entries with an extension of TXT E.* Find all entries starting with E X?X.* Find all three letter file names starting and ending with X mydir/* Find all entries in directory mydir NB: putting wildcards in the pathname will result in an error 'sort' specifies the sort order as follows: size by ascending size time by descending time/date name by file name (default if not specified) type by file extension
FLAG(n%)=value
Sets a bit in a system flag register. N% can be between 0 and 63 (i.e. 64 flag bits are available). Value can be 0 or 1. See also the FLAGS command and FLAG function and MM.FLAGS
FLAGS=value%
Sets all bits in the system flag register to the value specified. See also the FLAG command and the FLAGS function and MM.FLAGS
FLASH
Manages the storage of programs in the flash memory. Up to three programs can be stored in the flash memory and retrieved as required. Note that these saved programs will be erased with a firmware upgrade. One of these flash memory locations can be automatically loaded and run when power is applied using the OPTION AUTORUN n command. In the following ‘n’ is a number 1 to 3.
FLASH LIST
Displays a list of all flash locations including the first line of the program.
FLASH LIST n [,all]
List the program saved to slot n. Use ALL to list without page breaks.
FLASH ERASE n
Erase a flash program location.
FLASH ERASE ALL
Erase all flash program locations.
FLASH SAVE n
Save the current program to the flash location specified.
FLASH LOAD n
Load a program from the specified flash location into program memory.
FLASH RUN n
Runs the program in flash location n, clear all variables. Does not change the program memory.
FLASH CHAIN n
Runs the program in flash location n, leaving all variables intact (allows for a program that is much bigger than the program memory). Does not change the program memory. NB: if the chained program uses the READ command it must call RESTORE before the first read.
Page 112
PicoMite User Manual
FLASH OVERWRITE n
Erase a flash program location and then save the current program to the flash location specified.
FLASH DISK LOAD n, fname$ [,O[VERWRITE]]
Loads the contents of file fname$ into flash slot n as a binary image. The file can be created using LIBRARY DISK SAVE. Also, any file created externally with data required by a program can be loaded and accessed using commands like PEEK and MEMORY COPY using the address of the flash slot. If the optional parameter OVERWRITE (or O) is specified the content of the flash slot will be overwritten without an error being raised.
FLUSH [#]fnbr
Causes any buffered writes to a file previously opened with the file number ‘#fnbr’ to be written to disk. The # is optional. Using this command ensures that no data is lost if there is a power cut after a write command.
FONT [#]font-number, scaling
This will set the default font for displaying text on an LCD panel or the video output. Fonts are specified as a number. For example, #2 (the # is optional). See the chapter Graphics Commands and Functions 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. Eg, a scale of 2 will double the height and width.
FOR counter = start TO finish [STEP increment]
Initiates a FOR-NEXT loop with the 'counter' initially set to 'start' and incrementing in 'increment' steps (default is 1) until 'counter' is greater than 'finish'. The ‘increment’ can be an integer or a floating point number. Note that using a floating point fractional number for 'increment' can accumulate rounding errors in 'counter' which could cause the loop to terminate early or late. 'increment' can be negative in which case 'finish' should be less than 'start' and the loop will count downwards. See also the NEXT command.
FRAMEBUFFER
NOT HDMI AND VGA VERSIONS The Framebuffer command allow you to allocate some of the variable memory to either a framebuffer, a second display layer, or both and then use these in interesting ways to both avoid tearing artefacts and/or play graphics objects over the background display.
FRAMEBUFFER CREATE
Creates a framebuffer “F” with a RGB121 colour space and resolution to match the configured SPI colour display
FRAMEBUFFER LAYER
Creates a framebuffer “L” with a RGB121 colour space and resolution to match the configured SPI colour display
FRAMEBUFFER WRITE where/where$
Specifies the target for subsequent graphics commands. "where" can be N, F, or L where N is the actual display. AA string variable can be used or a literal
FRAMEBUFFER CLOSE [which]
Closes a framebuffer and releases the memory. The optional parameter "which" can be F or L. If omitted closes both.
FRAMEBUFFER COPY from, to [,b]
Does a highly optimised full screen copy of one framebuffer to another. "from" and "to" can be N, F, or L where N is the physical display. You can only copy from N on displays that support BLIT and transparent text. The firmware will automatically compress or expand the RGB resolution when copying to and from unmatched framebuffers.
PicoMite User Manual
Page 113
Of course copying from RGB565 to RGB121 loses information but for many applications (eg, games) 16 colour levels is more than enough. When copying to an LCD display the optional parameter “b” can be used (FRAMEBUFFER COPY F/L, N, B). This instructs the firmware to action the copy using the second CPU in the Raspberry Pi Pico and control returns immediately to the Basic program FRAMEBUFFER WAIT
Pauses processing until the LCD display enters frame blanking. Implemented for ILI9341, ST7789_320 and ILI9488 displays. Used to reduce artefacts when writing to the screen
FRAMEBUFFER MERGE [colour] [,mode] [,updaterate]
Copies the contents of the Layer buffer and Framebuffer onto the LCD display omitting all pixels of a particular colour. Preconditions for the command are that FRAMEBUFFER and LAYERBUFFER are both created FRAMEBUFFER MERGE - writes the contents of the framebuffer to the physical display overwriting any pixels in the framebuffer that are set in the layerbuffer (not zero) FRAMEBUFER MERGE col - writes the contents of the framebuffer to the physical display overwriting any pixels in the framebuffer that are in the layerbuffer not set to the transparent colour "col". The colour is specified as a number between 0 and 15 representing: 0:BLACK,1:BLUE,2:MYRTLE,3:COBALT,4:MIDGREEN,5:CERULEAN,6: GREEN,7:CYAN,8:RED,9:MAGENTA,10:RUST,11:FUCHSIA,12:BROWN, 13:LILAC,14:YELLOW,15:WHITE FRAMEBUFFER MERGE col,B - as above except that the transfer to the physical display takes place on the second CPU and control returns to Basic immediately FRAMEBUFFER MERGE col,R [,updaterate] - sets the second CPU to continuously update the physical display with the merger of the two buffers. Automatically sets FRAMEBUFFER WRITE F if not F or L already set. By default the screen will update as fast as possible (At 200MHz an ILI9341 in SPI mode updates about 13 times a second, in 8-bit parallel mode the ILI9341 achieves 27 FPS) If "updaterate" is set then the screen will update to the rate specified in milliseconds (unless that is less than the fastest achievable on the display) NB: FRAMEBUFFER WRITE cannot be set to N while continuous merged update is active. FRAMEBUFFER MERGE col,A - aborts the continuous updates In addition deleting either the layerbuf or framebuffer, ctrl-C, or END will abort the automatic update as well.
FRAMEBUFFER SYNC
Waits for the latest update on the second CPU to complete to allow drawing without tearing
FRAMEBUFFER
HDMI AND VGA VERSIONS ONLY The Framebuffer command allow you to allocate some of the variable memory to framebuffers, layer buffers, or both and then use these in interesting ways to both avoid tearing artefacts and/or play graphics objects over the background display.
FRAMEBUFFER CREATE
Creates a framebuffer “F” with a colour space and resolution to match the current display mode
FRAMEBUFFER CREATE 2
RP2350 only: Creates a second framebuffer “2” with a colour space and resolution to match the current display mode
Page 114
PicoMite User Manual
FRAMEBUFFER LAYER [colour]
Creates a layer buffer “L” with a colour space and resolution to match the current display mode. The optional parameter colour is specified as a number 0-15 (modes 2 and 3), RGB888 colour (mode 4) or 0-255 (mode 5) and specifies a colour which is ignored when the layer is applied to the display. In display modes where automatic layer application is not supported a layer buffer acts as another framebuffer.
FRAMEBUFFER LAYER TOP [colour]
RP2350 only: Creates a second layer buffer “T” with a colour space and resolution to match the current display mode. The optional parameter colour is specified as a number 0-15 (modes 2 and 3), 0-255 (mode 5) and specifies a colour which is ignored when the layer is applied to the display. In display modes where automatic 2nd layer application is not supported acts as another framebuffer.
FRAMEBUFFER WRITE where/where$
Specifies the target for subsequent graphics commands. "where" can be N, F, 2, T, or L where N is the actual display. A string variable can be used
FRAMEBUFFER CLOSE [which]
Closes a framebuffer and releases the memory. The optional parameter "which" can be F, 2, T or L. If omitted closes all.
FRAMEBUFFER COPY from, to [,b]
Does a highly optimised full screen copy of one framebuffer to another. "from" and "to" can be N, F, 2, T, or L where N is the physical display. If the optional parameter ‘b’ is specified pauses processing until the Monitor enters frame blanking.
FRAMEBUFFER WAIT
Pauses processing until the next frame blanking starts
FUNCTION xxx (arg1
[,arg2, …]) [AS
Defines a callable function. This is the same as adding a new function to
MMBasic while it is running your program.
'xxx' is the function name and it must meet the specifications for naming a
variable. The type of the function can be specified by using a type suffix (i.e.
xxx$) or by specifying the type using AS
PicoMite User Manual
Page 115
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 and have the correct type 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 and therefore may be accessed after the function has ended. The argument can be prefixed with BYVAL which will prevent this mechanism and cause only the value to be used. Alternatively, the prefix BYREF instructs MMBasic that a reference is required and an error will be generated if that cannot be done. Arrays are passed by specifying the array name with empty brackets (eg, arg()) and are always passed by reference and must be the correct type. You must not jump into or out of a function using commands like GOTO. Doing so will have undefined side effects including ruining your day. GAMEPAD COLOUR channel, colour
Changes the colour of the display panel on a PS4 controller on USB channel ‘channel’. ‘colour’ is set as a standard RGB888 value e.g. RGB(RED)
GAMEPAD HAPTIC channel left, right
Causes the left and right vibration motors to operate on a PS4 controller on USB channel ‘channel’. ’left’ and ‘right’ must be a number between 0 (off) and 255 (maximum).
GAMEPAD INTERRUPT ENABLE channel, int [,mask]
Enables interrupts on the button presses on a USB game controller. The optional parameter ‘mask’ defines which of the switches will trigger the interrupt (defaults to all). ‘mask’ is a bitmap corresponding to the output of the DEVICE(GAMEPAD channel,B) function.
GAMEPAD INTERRUPT DISABLE channel
Disables interrupts from the gamepad on the channel specified
GAMEPAD MONITOR
Use GAMEPAD MONITOR before plugging in a gamepad and when plugged in it will show the before and after report with each change of buttons
GAMEPAD CONFIGURE vid,pid,i0,c0,i1,c1,i2,c2,i3,c3,i 4,c4,i5,c5,i6,c6,i7,c7,i8,c8,i9,c 9,i10,c10,i11,c11,i12,c12,i13,c 13,i14,c14,i15,c15
Use to configure a gamepad that isn’t supported by the firmware. Run the command before plugging in the gamepad. All 34 parameters are mandatory. In each case the i/c parameters define the index into the report and the bit number at that index for the data that corresponds to the relevant bit. See DEVICE(GAMEPAD n,B) for more information on bit usage (0-15)
GOTO target
Branches program execution to the target, which can be a line number or a label.
GUI BITMAP x, y, bits [, width] [, height] [, scale] [, c] [, bc]
Displays the bits in a bitmap on a VGA/HDMI monitor or LCD panel starting at 'x' and 'y' on an attached device. 'height' and 'width' are the dimensions of the bitmap as displayed on the device 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
Page 116
PicoMite User Manual
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 chapter Graphics Commands and Functions for a definition of the colours and graphics coordinates.
GUI CALIBRATE or GUI CALIBRATE a,b,c,d,d
GUI TEST LCDPANEL
GUI RESET LCDPANEL
GUI TEST TOUCH
NOT VGA AND HDMI VERSIONS 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. The command can also be used with five arguments which specify the calibration values and in this case the calibration will be done without displaying any targets or requiring an input from the user. To discover the values use the OPTION LIST after calibrating the display normally. Note that these values are specific to that display and can vary considerably. Will test a display device (LCD, VGA, etc). It will continuously draw an animated display of colour circles on the display. NOT VGA AND HDMI VERSIONS Will reinitialise the configured LCD panel. Initialisation is automatically done when the PicoMite firmware starts up but in some circumstances it may be necessary to interrupt power to the LCD panel (eg, to save battery power) and this command can then be used to reinitialise the display. NOT VGA AND HDMI VERSIONS Will test the display touch feature on an LCD panel. The screen will be cleared and MMBasic will wait for a touch which will cause a white dot to be placed on the display marking the exact touch position on the screen. Any character entered at the console will terminate the test.
HELP searchtext
The help command looks for a file “help.txt” on the A: drive. This can be a user written or community developed file and must be in a particular format. For each help entry the first line must be a search string prefixed with a ~ character. This is used for the help functionality to find an entry and is not displayed. The ‘searchtext’ can contain ? for single character substitution or * for multiple character (or none) substitution. Following, the search string the next line would typically give the syntax of a particular command of function. Any subsequent lines would be further explanation. e.g. ~COLOR COLOR fore [, back] Sets the default color for commands (PRINT, etc) that display on the on the attached LCD panel. 'fore' is the foreground colour, 'back' is the background colour. The background is optional and if not specified will default to black. The command will return all entries that match the ‘searchtext’ and these will be paged to match the console device. Various versions of help.txt are available on https://www.thebackshed.com/forum/ViewTopic.php?FID=16&TID=17865
HUMID pin, tvar, hvar [,DHT11]
Returns the temperature and humidity using the DHT22 sensor. Alternative versions of the DHT22 are the AM2303 or the RHT03 (all are compatible). 'pin' is the I/O pin connected to the sensor. Any I/O pin may be used. 'tvar' is the variable that will hold the measured temperature and 'hvar' is the same for humidity. Both must be present and both must be floating point variables.
PicoMite User Manual
Page 117
For example: HUMID 3, 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. Normally the DHT22 should powered by 3.3V to keep its output below 3.6V for the Raspberry Pi Pico (the Pico 2 does not have this issue) and the signal pin of should be pulled up by a 1K to 10K resistor (4.7K recommended) to 3.3V. The optional DHT11 parameter modifies the timings to work with the DHT11. Set to 1 for DHT11 and 0 or omit for DHT22. I2C
More detail is in Appendix B
I2C OPEN speed, timeout
Enables the first I2C module in master mode. ‘speed’ is the clock speed (in KHz) to use and must be one of 100, 400 or 1000. ‘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).
I2C WRITE addr, option, sendlen, senddata [,sendata ..]
Send data to the I2C slave device. ‘addr’ is the slave’s I2C address. ‘option’ can be 0 for normal operation or 1 to keep control of the bus after the command (a stop condition will not be sent at the completion of the command) ‘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). Notes: The data can be supplied as individual bytes on the command line. Example: I2C WRITE &H6F, 0, 3, &H23, &H43, &H25 The data can be in a one dimensional array specified with empty brackets (i.e. no dimensions). ‘sendlen’ bytes of the array will be sent starting with the first element. Example: I2C WRITE &H6F, 0, 3, ARRAY() The data can be a string variable (not a constant). Example: I2C WRITE &H6F, 0, 3, STRING$
I2C READ addr, option, rcvlen, rcvbuf
Get data from the I2C slave device. ‘addr’ is the slave’s I2C address. ‘option’ can be 0 for normal operation or 1 to keep control of the bus after the command (a stop condition will not be sent at the completion of the command) ‘rcvlen’ is the number of bytes to receive. ‘rcvbuf’ is the variable or array used to save the received data - this can be: A string variable. Bytes will be stored as sequential characters. A one dimensional array of numbers specified with empty brackets. Received bytes will be stored in sequential elements of the array starting with the first. Example: I2C READ &H6F, 0, 3, ARRAY() A normal numeric variable (in this case rcvlen must be 1).
I2C CHECK addr
Will set the read only variable MM.I2C to 0 if a device responds at the address ‘addr’. MM.I2C will be set to 1 if there is no response.
I2C CLOSE
Disables the master I2C module. This command will also send a stop if the bus is still held.
I2C SLAVE
See Appendix B
Page 118
PicoMite User Manual
I2C2
The same set of commands as for I2C (above) but applying to the second I2C channel.
IF expr THEN stmt [: stmt] or IF expr THEN stmt ELSE stmt
Evaluates the expression ‘expr' and performs the statement following the THEN keyword if it is true or skips to the next line if false. If there are more statements on the line (separated by colons (:) they will also be executed if true or skipped if false. The ELSE keyword is optional and if present the statement(s) following it will be executed if 'expr' resolved to be false. The ‘THEN statement’ construct can be also replaced with: GOTO linenumber | label’. This type of IF statement is all on one line.
IF expression THEN
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.
INC var [,increment]
Increments the variable “var” by either 1 or, if specified, the value in increment. “increment” can be negative which will decrement. This is functionally the same as var = var + increment but is processed much faster
INPUT ["prompt$";] var1 [,var2 [, var3 [, etc]]]
Will take a list of values separated by commas (,) entered at the console and will assign them to a sequential list of variables. 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 The list of variables can be a mix of float, integer or string variables. The values entered at the console must correspond to the type of variable. If a single value is entered a comma is not required (however that value cannot contain a comma). ‘prompt$’ is a string constant (not a variable or expression) and if specified it will be printed first. Normally the prompt is terminated with a semicolon (;) and in that case a question mark will be printed following the prompt. If the prompt 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 or file previously opened for INPUT as ‘nbr’. See the OPEN command.
INTERRUPT [myint]
This command triggers a software interrupt. The interrupt is set up using INTERRUPT ‘myint’ where ‘myint’ is the name of a subroutine that will be executed when the interrupt is triggered. Use INTERRUPT 0 to disable the interrupt Use INTERRUPT without parameters to trigger the interrupt. Note: the interrupt can also be triggered from within a CSUB
IR dev, key , int or IR CLOSE
Decodes NEC or Sony infrared remote control signals. An IR Receiver Module is required to sense the IR light and demodulate the signal. It can be connected to any pin however this pin must be configured in advanced using the command: SETPIN n, IR
PicoMite User Manual
Page 119
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. Note that for the NEC protocol the bits in 'dev' and 'key' are reversed. For example, in 'key' bit 0 should be bit 7, bit 1 should be bit 6, etc. This does not affect normal use but if you are looking for a specific numerical code provided by a manufacturer you should reverse the bits. This describes how to do it: http://www.thebackshed.com/forum/forum_posts.asp?TID=8367 See the chapter 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 automatically 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 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 during which program execution is paused.
KEYPAD var, int, r1, r2, r3, r4, c1, 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. 'int' 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. r1, r2, r3 and r4 are pin numbers used for the four row connections to the keypad and c1, c2, c3 and c4 are the column connections. c4 is optional and is only used with 4x4 keypads. This command will automatically configure these pins as required. On a key press the value assigned to 'var' is the number of a numeric key (eg, '6' will return 6) or 10 for the * key and 11 for the # key. On 4x4 keypads the number 20 will be returned for A, 21 for B, 22 for C and 23 for D. The KEYPAD CLOSE command will terminate the keypad function and return the I/O pin to a not configured state. See the section Special Hardware Devices for more details.
KILL file$ [,all]
Deletes the file specified by ‘file$’. Any extension must be specified. Bulk erase is triggered if fname$ contains a '*' or a '?' character. If the optional 'all' parameter is used then you will be prompted for a single confirmation. If 'all' is not specified you will be prompted on each file.
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. 'd4' to 'd7' are the I/O pins that connect to inputs D4 to D7 on the LCD module (inputs D0 to D3 should be connected to ground). 'rs' is the pin connected to the register select input on the module (sometimes called CMD). 'en' is the pin connected to the enable or chip select input on the module. The R/W input on
Page 120
PicoMite User Manual
the module should always be grounded. The above I/O pins are automatically set to outputs by this command. When the module has been initialised data can be written to it using the LCD command. 'line' is the line on the display (1 to 4) and 'pos' is the character location on the line (the first location is 1). 'text$' is a string containing the text to write to the LCD display. 'pos' can also be C8, C16, C20 or C40 in which case the line will be cleared and the text centred on a 8 or 16, 20 or 40 line display. For example: LCD 1, C16, "Hello" LCD CLEAR will erase all data displayed on the LCD and LCD CLOSE will terminate the LCD function and return all I/O pins to the not configured state. See the chapter 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.
LET variable = expression
Assigns the value of 'expression' to the variable. LET is automatically assumed if a statement does not start with a command. For example: Var = 56
LIBRARY SAVE
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 the running program and act the same as the built in commands and functions in MMBasic. 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. See the heading The Library in this manual for a full explanation. The library is stored in program memory Flash Slot 3 which will then not be available for saving a program (slots 1 to 2 will still be available). LIBRARY SAVE will take whatever is in normal program memory, compress it (remove redundant data such as comments) and append 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 DELETE will remove the library and return Flash Slot 3 for normal use (OPTION RESET will do the same). LIBRARY LIST will list the contents of the library. Use ALL to list without page confirmations. LIBRARY DISK SAVE fname$ will save the current library as a binary file allowing a subsequent call to LIBRARY DISK LOAD fname$ to restore the library. Together, these allow libraries specific for individual programs to be stored and restored easily and distributed. Other than using version specific functionality in the library (WEB, VGA, GUI) libraries can be shared between versions.
or LIBRARY DELETE or LIBRARY LIST or LIBRARY LIST ALL or LIBRARY DISK SAVE fname$ or LIBRARY DISK LOAD fname$
LINE x1, y1, x2, y2 [, LW [, C]]
PicoMite User Manual
On an attached LCD display this command will draw a line starting at the coordinates ‘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
Page 121
defaults to 1 if not specified. ‘C’ is an integer representing the colour and defaults to the current foreground colour. All parameters can be expressed as arrays and the software will plot the number of lines as determined by the dimensions of the smallest array. 'x1', 'y1', 'x2', and 'y2' must all be arrays or all be single variables /constants otherwise an error will be generated. 'lw' and 'c' can be either arrays or single variables/constants. For horizontal and vertical lines that have a defined width and the x1 and y1 coordinate define the top-left pixel of the thick line. i.e. the line is to the right of the specified position or below it on the screen. For diagonal lines width a width > 1 the line is centered on the origin and destination pixels. If width is given as a -ve value then lines in all directions are centered on the given coordinates. LINE AA x1, y1, x2, y2 [, LW [, C]]
Draws a line with anti-aliasing . The parameters are as per the LINE command above. However this version will use variable intensity values of the specified colour to reduce the “staggered” quality of diagonal lines. In addition this version can draw diagonal lines of any width. Note that it does not accept arrays as parameters.
LINE GRAPH x(), y(), colour
This command generates a line graph of the coordinate pairs specified in “x()” and “y()”. The graph will have n-1 segments where there are n elements in the x and y arrays.
LINE INPUT [prompt$,] string-variable$
Reads an entire line from the console input into ‘string-variable$’. ‘prompt$’ is a string constant (not a variable or expression) and if specified it will be printed first. A question mark is not printed unless it is part of ‘prompt$’. Unlike INPUT, this command will read a whole line, not stopping for comma delimited data items.
LINE INPUT #nbr, string-variable$
Same as above except that the input is read from a serial communications port or a file previously opened for INPUT as ‘nbr’. See the OPEN command.
LINE PLOT ydata() [,nbr] [,xstart] [,xinc] [,ystart] [,yinc] [,colour]
Plots a line graph from an array of y-axis data points. ‘ydata()’ is an array of floats or integers to be plotted ‘nbr ‘is the number of line segments to be plotted - defaults to the lesser of the array size and MM.HRES-2 if omitted ‘xstart’ is the x-coordinate to start plotting - defaults to 0 ‘xinc’ is the increment along the x-axis to plot each coordinate - defaults to 1 ‘ystart’ is the location in ydata to start the plot - defaults to the array start. NB: respects OPTION BASE ‘yinc’ is the increment to the index into ydata to add for each point to be plotted ‘colour’ is the colour to draw the line
LIST [fname$] or LIST ALL [fname$]
List a program on the 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 to a terminal emulator on a PC that has the ability to capture its input stream to a file. I f the optional ‘fname$’ is specified then that file on the Flash Filesystem or SD Card will be listed.
LIST PINS
Lists the current status of all pins on the processor
LIST SYSTEM I2C
Lists a map of all I2C devices connected to the system I2C bus
Page 122
PicoMite User Manual
LIST COMMANDS or LIST FUNCTIONS
Lists all valid commands or functions
LIST VARIABLES [s%()]
Lists all global variables and contants and, if invoked in a subroutine, the variable used by that subroutine and any subroutines that called it. If the optional parameter s$() is used the variables will be listed to s%() treated as a longstring (see LONGSTRING command).
LOAD file$ [,R]
Loads a program called ‘file$’ from the Flash Filesystem or SD Card into program memory. If the optional suffix ,R is added the program will be immediately run without prompting (in this case ‘file$’ must be a string constant). The RUN command does the same thing and allows a string variable to be used. If an extension is not specified “.BAS” will be added to the file name.
LOAD CONTEXT [KEEP]
Restores the variable space to the previously saved state and optionally preserves the stored variables to allow a second LOAD if required. See also SAVE CONTEXT
LOAD IMAGE file$ [, x] [, y]
Load a bitmapped image (BMP) from the Flash Filesystem or SD Card and display it on the display. ''file$' is the name of the file and 'x' and 'y' are the screen coordinates for the top left hand corner of the image. If the coordinates are not specified the image will be drawn at the top left hand position on the screen. If an extension is not specified “.BMP” will be added to the file name. All types of the BMP format are supported including black and white and true colour 24-bit images.
LOAD JPG file$ [, x] [, y]
Load a jpg image from the Flash Filesystem or SD Card and display it on the display. ''file$' is the name of the file and 'x' and 'y' are the screen coordinates for the top left hand corner of the image. If the coordinates are not specified the image will be drawn at the top left hand position on the screen. If an extension is not specified “.JPG” will be added to the file name. Progressive jpg images are not supported.
LOAD PNG fname$ [, x] [, y] [,transparent] [,alphacut]
Loads and displays a png file 'fname' If no extension is specified .png will be automatically added to the filename. The file must be in RGBA8888 format which is the normal default. If specified 'x' and 'y' indicate where on the display or framebuffer the image will appear. The optional parameter 'transparent' (defaults to 0) specifies one of the colour codes (0-15) which will be allocated to pixels in the png file with an alpha value less than 'alphacut' (defaults to 20). If 'transparent' is set to -1 the png image is written with pixels with an alpha value less than 'alphacut' missed completely.
LOCAL variable [, variables] See DIM for the full syntax.
Defines a list of variable names as local to the subroutine or function. This command uses exactly the same syntax as DIM and will create variables that will only be visible within the subroutine or function. They will be automatically discarded when the subroutine or function exits.
LONGSTRING
The LONGSTRING commands allow for the manipulation of strings longer than the normal MMBasic limit of 255 characters. Variables for holding long strings must be defined as single dimensioned integer arrays with the number of elements set to the number of characters
PicoMite User Manual
Page 123
required for the maximum string length divided by eight. The reason for dividing by eight is that each integer in an MMBasic array occupies eight bytes. Note that the long string routines do not check for overflow in the length of the strings. If an attempt is made to create a string longer than a long string variable's size the outcome will be undefined. LONGSTRING AES128 ENCRYPT/DECRYPT CBC/ECB/CTR key$/key!/%, in%(), out%() [,iv$/iv!/%]
Encrypts or decrypts the longstring in in%() putting the answer in out%() For CBC and CTR modes the encryption will generate a random initialisation vector and prepend out%() with the IV. If an explicit IV is specified this will be used instead of the random vector and this will be prepended to out%() For CBC and CTR decryption the firmware assumes that the first 16 bytes of in%() are the initialisation vector. In the case where you want to transmit a message without IV you can use LONGSTRING RIGHT to remove the IV before sending the message. In this case the recipient must know the IV as well as the key and create a complete longstring before using DECRYPT. This can be done by using LONGSTRING CONCAT to add the incoming message to a longstring containing the IV.
LONGSTRING APPEND array%(), string$
Append a normal MMBasic string to a long string variable. ‘array%()’ is a long string variable while ‘string$’ is a normal MMBasic string expression.
LONGSTRING BASE64 ENCODE/DECODE in%(), out%()
This BASE64 encodes or decodes the longstring in in%() placing the answer in out%(). The array used as the output must be big enough relative to the input and the direction. Encoding increases length by 4/3 and decoding decreases it by 3/4
LONGSTRING CLEAR array%()
Will clear the long string variable ‘array%()’. i.e. it will be set to an empty string.
LONGSTRING COPY dest%(), src%()
Copy one long string to another. ‘dest%()’ is the destination variable and ‘src%()’ is the source variable. Whatever was in ‘dest%()’ will be overwritten.
LONGSTRING CONCAT dest%(), src%()
Concatenate one long string to another. ‘dest%()’ is the destination variable and ‘src%()’ is the source variable. ‘src%()’ will the added to the end of ‘dest%()’ (the destination will not be overwritten).
LONGSTRING LCASE array%()
Will convert any uppercase characters in ‘array%()’ to lowercase. ‘array%()’ must be long string variable.
LONGSTRING LEFT dest%(), src%(), nbr
Will copy the left hand 'nbr' characters from ‘src%()’ to ‘dest%()’ overwriting whatever was in ‘dest%()’. i.e. copy from the beginning of ‘src%()’. ‘src%()’ and ‘dest%()’ must be long string variables. 'nbr' must be an integer constant or expression.
LONGSTRING LOAD array%(), nbr, string$
Will copy 'nbr' characters from ‘string$’ to the long string variable ‘array%()’ overwriting whatever was in ‘array%()’.
LONGSTRING MID dest%(), src%(), start, nbr
Will copy 'nbr' characters from ‘src%()’ to ‘dest%()’ starting at character position 'start' overwriting whatever was in ‘dest%()’. i.e. copy from the middle of ‘src%()’. 'nbr' is optional and if omitted the characters from 'start' to the end of the string will be copied ‘src%()’ and ‘dest%()’ must be long string variables. 'start' and 'nbr' must be integer constants or expressions.
LONGSTRING PRINT [#n,] src%() [;]
Prints the longstring stored in ‘src%()’ to the file or COM port opened as ‘#n’. If ‘#n’ is not specified the output will be sent to the console. Add a semi-colon to supress CR/LF.
LONGSTRING REPLACE array%() , string$, start
Will substitute characters in the normal MMBasic string ‘string$’ into an existing long string ‘array%()’ starting at position ‘start’ in the long string.
Page 124
PicoMite User Manual
LONGSTRING RESIZE addr%(), nbr
Sets the size of the longstring to ‘nbr’. This overrides the size set by other longstring commands so should be used with caution. Typical use would be in using a longstring as a byte array.
LONGSTRING RIGHT dest%(), src%(), nbr
Will copy the right hand 'nbr' characters from ‘src%()’ to ‘dest%()’ overwriting whatever was in ‘dest%()’. i.e. copy from the end of ‘src%()’. ‘src%()’ and ‘dest%()’ must be long string variables. 'nbr' must be an integer constant or expression.
LONGSTRING SETBYTE addr%(), nbr, data
Sets byte ‘nbr’ to the value “data”, ‘nbr’ respects OPTION BASE
LONGSTRING TRIM array%(), nbr
Will trim ‘nbr’ characters from the left of a long string. ‘array%()’ must be a long string variables. 'nbr' must be an integer constant or expression.
LONGSTRING UCASE array%()
Will convert any lowercase characters in ‘array%()’ to uppercase. ‘array%()’ must be long string variable.
LOOP [UNTIL expression]
Terminates a program loop: see DO.
MAP
HDMI VERSION ONLY The MAP commands allow the programmer to set the colours used in 4 or 8-bit colour modes. Each value in the 4 or 8-bit colour pallet can be set to an independent 24-bit colour (ie, RGB555 format). See the MAP function for more information
MAP( n ) = rgb%
This will assign the 24-bit colour 'rgb% to all pixels with the 4 or 8-bit colour value of 'n'. The change is activated after the MAP SET command.
MAP MAXIMITE
This will set the colour map to the colours implemented in the original Colour Maximite.
MAP GREYSCALE
This will set the colour map to 16 or 32 levels of grey (depending on the MODE). MAP GRAYSCALE is also valid.
MAP SET
This will cause MMBasic to update the colour map (set using MAP(n)=rgb%) during the next frame blanking interval.
MAP RESET
This will reset the colour map to the default colours
MAP
VGA VERSION ONLY The MAP commands allow the programmer to select the colours used in 4-bit colour modes. Each value in the 4-bit colour pallet can be set to one of the 16 available colours . See the MAP function for more information.
MAP( n ) = rgb%
This will assign the 24-bit colour 'rgb% to all pixels with the 4-bit colour value of 'n'. The RGB value is converted to one of the available 16 VGA RGB121 colours as set by the resistor network. The change is activated after the MAP SET command.
MAP MAXIMITE
This will set the colour map to the colours implemented in the original Colour Maximite.
MAP SET
This will cause MMBasic to update the colour map (set using MAP(n)=rgb%) during the next frame blanking interval.
PicoMite User Manual
Page 125
MAP RESET
This will reset the colour map to the default colours which in 4-bit mode are: ‘n’ Colour Value 15 WHITE RGB(255, 255, 255) 14 YELLOW RGB(255, 255, 0) 13 LILAC RGB(255, 128, 255) 12 BROWN RGB(255, 128, 0) 11 FUCHSIA RGB(255, 64, 255) 10 RUST RGB(255, 64, 0) 9 MAGENTA RGB(255, 0, 255) 8 RED RGB(255, 0, 0) 7 CYAN RGB(0, 255, 255) 6 GREEN RGB(0, 255, 0) 5 CERULEAN RGB(0, 128, 255) 4 MIDGREEN RGB(0, 128, 0) 3 COBALT RGB(0, 64, 255) 2 MYRTLE RGB(0, 64, 0) 1 BLUE RGB(0, 0, 255) 0 BLACK RGB(0, 0, 0)
MATH
The math command performs many simple mathematical calculations that can be programmed in BASIC but there are speed advantages to coding looping structures in the firmware and there is the advantage that once debugged they are there for everyone without re-inventing the wheel. Note: 2 dimensional maths matrices are always specified DIM matrix(n_columns, n_rows) and of course the dimensions respect OPTION BASE. Quaternions are stored as a 5 element array w, x, y, z, magnitude.
MATH RANDOMIZE [n]
Seeds the Mersenne Twister algorithm. If n is not specified the seed is the time in microseconds since boot The Mersenne Twister algorithm gives a much better random number than the C-library inbuilt function
Simple array arithmetic MATH SET nbr, array()
See ARRAY SET
MATH SCALE in(), scale ,out()
This scales the matrix in() by the scalar scale and puts the answer in out(). Works for arrays of any dimensionality of both integer and float and can convert between. Setting b to 1 is optimised and is the fastest way of copying an entire array.
MATH ADD in(), num ,out()
See ARRAY ADD
MATH INTERPOLATE in1(), in2(), ratio, out()
This command implements the following equation on every array element: out = (in2 - in1) * ratio + in1 Arrays can have any number of dimensions and must be distinct and have the same number of total elements. The command works with both integer and floating point arrays in any mixture
This command takes the “in” array and scales it between “minout” and MATH WINDOW in(), minout, maxout, out() [,minin!, “maxout” returning the answer in “out”. Optionally, it can also return the minimum and maximum floating point values found in the original data maxin!] (“minin!” and “maxin!”). Note: “minout” can be greater than “maxout” and in this case the data will be both scaled and inverted. e.g
Page 126
PicoMite User Manual
DIM IN(2)=(1,2,3) DIM OUT(2) MATH WINDOW IN(),7,3,OUT(),LOW,HIGH Will return OUT(0)=7, OUT(1)=5,OUT(2)=3,LOW=1,HIGH=3 This command can massively simplify scaling data for plotting etc. MATH SLICE sourcearray(), [d1] [,d2] [,d3] [,d4] [,d5] , destinationarray()
See ARRAY SLICE
MATH INSERT targetarray(), [d1] [,d2] [,d3] [,d4] [,d5] , sourcearray()
See ARRAY INSERT
MATH POWER inarray(), power, outarray()
Raises each element in ‘inarray()’ to the ‘power’ defined and puts the output in ‘outarray()’
MATH SHIFT inarray%(), nbr, outarray%() [,U]
This command does a bit shift on all elements of inarray%() and places the result in outarray%() (may be the same as inarray%()). nbr can be between -63 and 63. Positive numbers are a left shift (multiply by power of 2). Negative number are a right shift. The optional parameter ,U will force an unsigned shift.
Matrix arithmetic
MATH M_INVERSE array!(), inversearray!()
This returns the inverse of array!() in inversearray!(). The array must be square and you will get an error if the array cannot be inverted (determinant=0). array!() and inversearray!() cannot be the same.
MATH M_PRINT array()
Quick mechanism to print a 2D matrix one row per line.
MATH M_TRANSPOSE in(), out()
Transpose matrix in() and put the answer in matrix out(), both arrays must be 2D but need not be square. If not square then the arrays must be dimensioned in(m,n) out(n,m)
MATH M_MULT in1(), in2(), out()
Multiply the arrays in1() and in2() and put the answer in out()c. All arrays must be 2D but need not be square. If not square then the arrays must be dimensioned in1(m,n) in2(p,m) ,out(p,n)
Vector arithmetic MATH V_PRINT array() [,hex]
Quick mechanism to print a small array on a single line. ‘hex’ will print in hex.
MATH V_NORMALISE inV(), outV()
Converts a vector inV() to unit scale and puts the answer in outV() (sqr(xx + yy +....)=1 There is no limit on number of elements in the vector
MATH V_MULT matrix(), inV(), outV()
Multiplies matrix() and vector inV() returning vector outV(). The vectors and the 2D matrix can be any size but must have the same cardinality.
MATH V_CROSS inV1(), inV2(), outV()
Calculates the cross product of two three element vectors inV1() and inV2() and puts the answer in outV()
MATH V_ROTATE x, y, a, xin(), yin(), xout(), yout()
This command rotates the coordinate pairs in “xin()” and “yin()” around the centre point defined by “x” and “y” by the angle “a” and puts the results in “xout()” and “yout()”. NB: the input and output arrays can be the same and the
PicoMite User Manual
Page 127
Quaternion arithmetic
rotation angle is, by default, in radians but this can be changed using the OPTION ANGLE command.
MATH Q_INVERT inQ(), outQ()
Invert the quaternion in inQ() and put the answer in outQ()
MATH Q_VECTOR x, y, z, outVQ()
Converts a vector specified by x , y, and z to a normalised quaternion vector outVQ() with the original magnitude stored
MATH Q_CREATE theta, x, y, z, outRQ()
Generates a normalised rotation quaternion outRQ() to rotate quaternion vectors around axis x,y,z by an angle of theta. Theta is specified in radians.
MATH Q_EULER yaw, pitch, roll, outRQ()
Generates a normalised rotation quaternion outRQ() to rotate quaternion vectors as defined by the yaw, pitch and roll angles With the vector in front of the “viewer” yaw is looking from the top of the ector and rotates clockwise, pitch rotates the top away from the camera and roll rotates around the z-axis clockwise. The yaw, pitch and roll angles default to radians but respect the setting of OPTION ANGLE
MATH Q_MULT inQ1(), inQ2(), outQ()
Multiplies two quaternions inQ1() and inQ2() and puts the answer in outQ()
MATH Q_ROTATE , RQ(), inVQ(), outVQ()
Rotates the source quaternion vector inVQ() by the rotate quaternion RQ() and puts the answer in outVQ()
MATH C_ADD array1%(), array2%(), array3%() MATH C_SUB array1%(), array2%(), array3%() MATH C_MUL array1%(), array2%(), array3%() MATH C_DIV array1%(), array2%(), array3%() MATH C_ADD array1!(), array2!(), array3!() MATH C_SUB array1!(), array2!(), array3!() MATH C_MUL array1!(), array2!(), array3!() MATH C_DIV array1!(), array2!(), array3!()
These commands do cell by cell operations (hence C_) on identically sized arrays. There are no restrictions on the number of dimensions and no restrictions on using the same array twice or even three times in the parameters. The datatype must be the same for all the arrays. eg, MATH C_MUL a%(),a%(),a%() will square all the values in the array a%()
MATH FFT signalarray!(), FFTarray!()
Performs a fast fourier transform of the data in “signalarray!”. "signalarray" must be floating point and the size must be a power of 2 (eg, s(1023) assuming OPTION BASE is zero) "FFTarray" must be floating point and have dimension 2*N where N is the same as the signal array (eg, f(1,1023) assuming OPTION BASE is zero) The command will return the FFT as complex numbers with the real part in f(0,n) and the imaginary part in f(1,n)
MATH FFT INVERSE FFTarray!(), signalarray!()
Performs an inverse fast fourier transform of the data in “FFTarray!”. "FFTarray" must be floating point and have dimension 2*N where N must be a power of 2 (eg, f(1,1023) assuming OPTION BASE is zero) with the real part in f(0,n) and the imaginary part in f(1,n). "signalarray" must be floating point and the single dimension must be the same as the FFT array. The command will return the real part of the inverse transform in "signalarray".
MATH FFT MAGNITUDE signalarray!(),magnitudearray! ()
Generates magnitudes for frequencies for the data in “signalarray!” "signalarray" must be floating point and the size must be a power of 2 (eg, s(1023) assuming OPTION BASE is zero). "magnitudearray" must be floating point and the size must be the same as the signal array The command will return the magnitude of the signal at various frequencies according to the formula:
Page 128
PicoMite User Manual
frequency at array position N = N * sample_frequency / number_of_samples MATH FFT PHASE signalarray!(), phasearray!()
Generates phases for frequencies for the data in “signalarray!”. "signalarray" must be floating point and the size must be a power of 2 (eg, s(1023) assuming OPTION BASE is zero). "phasearray" must be floating point and the size must be the same as the signal array The command will return the phase angle of the signal at various frequencies according to the formula above.
MATH SENSORFUSION type ax, ay, az, gx, gy, gz, mx, my, mz, pitch, roll, yaw [,p1] [,p2]
Type can be MAHONY or MADGWICK Ax, ay, and az are the accelerations in the three directions and should be specified in units of standard gravitational acceleration. Gx, gy, and gz are the instantaneous values of rotational speed which should be specified in radians per second. Mx, my, and mz are the magnetic fields in the three directions and should be specified in nano-Tesla (nT) Care must be taken to ensure that the x, y and z components are consistent between the three inputs. So , for example, using the MPU-9250 the correct input will be ax, ay,az, gx, gy, gz, my, mx, -mz based on the reading from the sensor. Pitch, roll and yaw should be floating point variables and will contain the outputs from the sensor fusion. The SENSORFUSION routine will automatically measure the time between consecutive calls and will use this in its internal calculations. The Madwick algorithm takes an optional parameter p1. This is used as beta in the calculation. It defaults to 0.5 if not specified The Mahony algorithm takes two optional parameters p1, and p2. These are used as Kp and Ki in the calculation. If not specified these default to 10.0 and 0.0 respectively. A fully worked example of using the code is given on the BackShed forum at: https://www.thebackshed.com/forum/ViewTopic.php?TID=13459&PID=1669 62#166962
MATH PID INIT channel, pid_params!(), callback
This command sets up a PID controller that can work automatically in the background. Up to 8 PID controllers can run simultaneously (channels 1 to 8) ‘callback’ is a MMbasic subroutine which is called at the rate defined by the sample time. See the MATH(PID …) function for details of what should be included in the subroutine. The pid_params!() array must be dimensioned for all the listed elements, including the controller memory parameters (DIM pid_params!(13)) and be initialised with the required settings. PID configuration Element 0 = Kp Element 1 = Ki Element 2 = Kd Element 3 = tau ' Derivative low-pass filter time constant Element 4 = limMin 'Output limits Element 5 = limMax Element 6 = limMinInt 'Integrator limits Element 7 = limMaxInt Element 8 = T 'Sample time (in seconds) Controller "memory" Element 9 = integrator
PicoMite User Manual
Page 129
Element 10 = prevError Element 11 = differentiator Element 12 = prevMeasurement Element 13 = out MATH PID START channel
Starts a previously initialised PID controller on the channel specified
MATH PID STOP channel
Stops a previously initialised PID controller on the channel specified and deletes the internal data structures See https://www.thebackshed.com/forum/ViewTopic.php?FID=16&TID=17263 For an example of setting up and running a PID controller
MATH AES128 ENCRYPT/DECRYPT CBC/ECB/CTR key$/key(), in$/in(), out$/out() [,iv$/iv()]
This command encrypts or decrypts the data in 'in' and puts the answer in 'out' using the AES128 encryption method specified The parameters can each be either a string, integer array, or float array with any mix possible The key must be 16 elements long (168=128bits), in and out must be a multiple of 16 elements long. In the case of out being specified as a string (e.g. out$), the string variable must exist and should be set to empty (DIM out$="") The maximum number of elements in 'in' and 'out' is limited by memory when defined as arrays. Strings for encrypting are limited to 240bytes (EBR) and 224bytes (CTR and CBC). For CBC and CTR encryption you can optionally specify an initialisation vector 'iv'. 'iv' must be 16 elements long (168=128bits). If an initialisation vector is not specified encryption will generate a random initialisation vector. In both cases the output is prepended with the IV. For CBC and CTR, decryption requires that the first 16 elements of the input are the initialisation vector. In the case where you want to transmit a message without IV you should remove the IV before sending the message using standard MMBasic manipulations. In this case the recipient must know the IV as well as the key and create a complete message before using DECRYPT by prepending the IV to the incoming message.
MEMORY
List the amount of memory currently in use. For example: Program: 0K ( 0%) Program (0 lines) 180K (100%) Free Saved Variables: 16K (100%) Free RAM: 0K ( 0%) 0 Variables 0K ( 0%) General 228K (100%) Free Notes: Memory usage is rounded to the nearest 1K byte. General memory (RAM) is used by arrays, strings, serial I/O buffers, etc.
MEMORY SET address, byte, numberofbytes
Page 130
This command will set a region of memory to a value. BYTE = One byte per memory address.
PicoMite User Manual
MEMORY SET BYTE address, byte, numberofbytes MEMORY SET SHORT address, short, numberofshorts
SHORT = Two bytes per memory address. WORD = Four bytes per memory address. FLOAT = Eight bytes per memory address. ‘increment’ is optional and controls the increment of the ‘address’ pointer as the operation is executed. For example, if increment=3 then only every third element of the target is set. The default is 1.
MEMORY SET WORD address, word, numberofwords MEMORY SET INTEGER address, integervalue ,numberofintegers [,increment] MEMORY SET FLOAT address, floatingvalue ,numberofloats [,increment] MEMORY COPY sourceaddress, destinationaddres, numberofbytes [,sourceincrement][,destination increment] MEMORY COPY INTEGER sourceaddress, destinationaddress, numberofintegers [,sourceincrement][,destination increment]
This command will copy one region of memory to another. COPY INTEGER and FLOAT will copy eight bytes per operation. ‘sourceincrement’ is optional and controls the increment of the ‘sourceaddress’ pointer as the operation is executed. For example, if sourceincrement=3 then only every third element of the source will be copied. The default is 1. ‘destinationincrement’ is similar and operates on the ‘destinationaddress’ pointer.
MEMORY COPY FLOAT sourceaddress, destinationaddress, numberoffloats [,sourceincrement][,destination increment] MEMORY PRINT #]fnbr , nbr, address%/array() MEMORY INPUT [#]fnbr , nbr, address%/array() MEMORY PACK source%()/sourceaddress%, dest%()/destaddress%, number, size MEMORY UNPACK source%()/sourceaddress%, dest%()/destaddress%, number, size
PicoMite User Manual
These commands save or read ‘nbr’ of data bytes from or to memory from or to an open disk file. The memory to be saved can be specified as an integer array in which case the nbr of bytes to be saved or read is checked against the array size. Alternatively, a memory address can be used in which case no checking can take place and user errors could result in a crash of the firmware.. Memory pack and unpack allow integer values from one array to be compressed into another or uncompressed from one to the other. The two arrays are always normal integer arrays but the packed array can have 2, 4, 8, 16 or 64 values “packed into them. Thus a single integer array element could store 2 off 32-bit words, 4 off 16 bit values, 8 bytes, 16 nibbles, or 64 booleans (bits). “number specifies the number of values to be packed or unpacked and “size” specifies the number of bits (1,4,8,16,or 32) Alternatively, memory address(es) can be used in which case no checking can take place and user errors could result in a crash of the firmware.
Page 131
MKDIR dir$
Make, or create, the directory ‘dir$’ on the default Flash Filesystem or SD Card.
MID$( str$, start, num) = str2$
The ‘num’ characters in 'str$', beginning at position 'start', are replaced by the characters in 'str2$'.
MODE 1 or MODE 2 Or MODE 3 (RP2350 only)
VGA VERSIONS ONLY VGA video supports a number of resolutions (see OPTION RESOLUTION). This command will select the mode ‘n’ depending on the resolution: OPTION RESOLUTION 640 x 480 MODE 1 640 x 480 x 2 colours (monochrome). Default at startup. Tiles width is fixed at 8 pixels. Tile height defaults to 12 pixels but can be from 8 to MM.HRES. Tiles colours are specified using the standard RGB888 notation. This is converted to RGB121. A framebuffer (F) and a layer buffer (L) can be created. These have no impact on the display and do not use user memory but both can be used for creating images and copying to the display screen (N) MODE 2 320 x 240 x 16 colours. RGB121 format (i.e. 1 bit for red, 2 bits for green, and 1 bit for blue). A framebuffer (F) can be created. This have no impact on the display and does not use user memory but can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This also does not use user memory. any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours of the 16 available. The hardware is limited to the 16 colours defined by the resistor network MODE 3 640 x 480 x 16 colours. RGB121 format (i.e. 1 bit for red, 2 bits for green, and 1 bit for blue). A framebuffer (F) can be created. This have no impact on the display and does not use user memory but can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This also does not use user memory. any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours of the 16 available. The hardware is limited to the 16 colours defined by the resistor network OPTION RESOLUTION 720 x 400 MODE 1 720 x 400 x 2 colours (monochrome). Default at startup. Tiles width is fixed at 8 pixels. Tile height defaults to 12 pixels but can be from 8 to MM.HRES. Tiles colours are specified using the standard RGB888 notation. This is converted to RGB121. A framebuffer (F) and a layer buffer (L) can be created. These have no impact on the display and do not use user memory but both can be used for creating images and copying to the display screen (N) MODE 2 360 x 200 x 16 colours. RGB121 format (i.e. 1 bit for red, 2 bits for green, and 1 bit for
Page 132
PicoMite User Manual
blue). A framebuffer (F) can be created. This have no impact on the display and does not use user memory but can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This also does not use user memory. any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours of the 16 available In the case of VGA, the hardware is limited to the 16 colours defined by the resistor network MODE 3 720 x 400 x 16 colours. RGB121 format (i.e. 1 bit for red, 2 bits for green, and 1 bit for blue). A framebuffer (F) can be created. This have no impact on the display and does not use user memory but can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This also does not use user memory. any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours of the 16 available. In the case of VGA, the hardware is limited to the 16 colours defined by the resistor network OPTION RESOLUTION 800 x 600 (RP2350 only) MODE 1 800 x 600 x 2 colours (monochrome). Default at startup. Tiles width is fixed at 8 pixels. Tile height defaults to 12 pixels but can be from 8 to MM.HRES. Tiles colours are specified using the standard RGB888 notation. This is converted to RGB121. A framebuffer (F) and a layer buffer (L) can be created. These have no impact on the display and do not use user memory but both can be used for creating images and copying to the display screen (N) MODE 2 400 x 300 x 16 colours. RGB121 format (i.e. 1 bit for red, 2 bits for green, and 1 bit for blue). A framebuffer (F) can be created. This have no impact on the display and does not use user memory but can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This also does not use user memory. any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours of the 16 available The hardware is limited to the 16 colours defined by the resistor network MODE 3 800 x 600 x 16 colours. RGB121 format (i.e. 1 bit for red, 2 bits for green, and 1 bit for blue). A framebuffer (F) can be created. This have no impact on the display and does not use user memory but can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This also does not use user memory. any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default
PicoMite User Manual
Page 133
colours of the 16 available, The hardware is limited to the 16 colours defined by the resistor network OPTION RESOLUTION 848 x 480 (RP2350 only) MODE 1 848 x 480 x 2 colours (monochrome). Default at startup. Tiles width is fixed at 8 pixels. Tile height defaults to 12 pixels but can be from 8 to MM.HRES. Tiles colours are specified using the standard RGB888 notation. This is converted to RGB121. A framebuffer (F) and a layer buffer (L) can be created. These have no impact on the display and do not use user memory but both can be used for creating images and copying to the display screen (N) MODE 2 424 x 240 x 16 colours. RGB121 format (i.e. 1 bit for red, 2 bits for green, and 1 bit for blue). A framebuffer (F) can be created. This have no impact on the display and does not use user memory but can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This also does not use user memory. any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours of the 16 available The hardware is limited to the 16 colours defined by the resistor network MODE 3 848 x 48 x 16 colours. RGB121 format (i.e. 1 bit for red, 2 bits for green, and 1 bit for blue). A framebuffer (F) can be created. This have no impact on the display and does not use user memory but can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This also does not use user memory. any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours of the 16 available, The hardware is limited to the 16 colours defined by the resistor network MODE n
HDMI VERSIONS ONLY HDMI video supports a number of resolutions (see OPTION RESOLUTION). This command will select the mode ‘n’ depending on the resolution: OPTION RESOLUTION 640 x 480 MODE 1 640 x 480 x 2-colours (monochrome). Default at startup. Use the TILE command as normal. Tiles width is fixed at 8 pixels. Tile height defaults to 12 pixels but can be from 8 to MM.HRES. Tiles colours are specified using the standard RGB888 notation. This is converted to RGB555. A framebuffer (F) and a layer buffer (L) can be created. These can be used for creating images and copying to the display screen (N) MODE 2 320 x 240 x 16 colours. A framebuffer (F) can be created. This can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. Any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show
Page 134
PicoMite User Manual
MODE 3
MODE 4
MODE 5
allowing the main display buffer to show through. Map functionality is available to override the default colours. 640 x 480 x 16 colours. Colour mapping to RGB555 palette. A framebuffer (F) can be created. It can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. Any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. 320 x 240 x 32768 colours. This is full RGB555 allowing good quality colour images to be displayed. A framebuffer (F) and a layer buffer (L) can be created. These have no impact on the display and can be used for creating images and copying to the display screen (N). Only one can be created 320 x 240 x 256 colours. A framebuffer (F) can be created. This has no impact on the display. It can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This does not use user memory. Any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-255: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours of the 256 available. Each of the 256 colours can be mapped to any RGB555 colour.
OPTION RESOLUTION 720 x 400 MODE 1 720 x 400 x 2-colours (monochrome). Default at startup. Use the TILE command as normal. Tiles width is fixed at 8 pixels. Tile height defaults to 12 pixels but can be from 8 to MM.HRES. Tiles colours are specified using the standard RGB888 notation. This is converted to RGB555. A framebuffer (F) and a layer buffer (L) can be created. These can be used for creating images and copying to the display screen (N) MODE 2 360 x 200 x 16 colours. A framebuffer (F) can be created. This can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. Any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours. MODE 3 720 x 400 x 16 colours. Colour mapping to RGB555 palette. A framebuffer (F) can be created. It can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. Any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-15: defaults to 0) which does not show allowing the main display buffer to show through. MODE 4 360 x 200 x 32768 colours. This is full RGB555 allowing good quality colour images to be PicoMite User Manual
Page 135
displayed. A framebuffer (F) and a layer buffer (L) can be created. These have no impact on the display and can be used for creating images and copying to the display screen (N). Only one can be created MODE 5 360 x 200 x 256 colours. A framebuffer (F) can be created. This has no impact on the display. It can be used for creating images and copying to the display screen (N). In addition a layer buffer can be created. This does not use user memory. Any pixels written to the layer buffer will automatically appear on the display sitting on top of whatever may be in the main display buffer. A colour can be specified (0-255: defaults to 0) which does not show allowing the main display buffer to show through. Map functionality is available to override the default colours of the 256 available. Each of the 256 colours can be mapped to any RGB555 colour. OPTION RESOLUTION 800 x 600 MODE 1 800 x 600 x 2-colours with RGB332 tiles (use the TILE command as normal) MODE 2 400 x 300 x 16colours with optional layer and colour mapping to RGB332 palette MODE 3 800 x 400 x 16 colours with optional layer and colour mapping to RGB332 palette MODE 5 400 x 300 x 256 colours with optional layer (no memory usage) OPTION RESOLUTION 848 x 480 MODE 1 848 x 480 x 2-colours with RGB332 tiles (use the TILE command as normal) MODE 2 424 x 240 x 16colours with optional layer and colour mapping to RGB332 palette MODE 3 848 x 480 x 16 colours with optional layer and colour mapping to RGB332 palette MODE 5 424 x 240 x 256 colours with optional layer (no memory usage) OPTION RESOLUTION 1280 x 720 MODE 1 1280 x 720 x 2-colours with RGB332 tiles (use the TILE command as normal) MODE 2 320 x 180 x 16colours with 2 optional layers and colour mapping to RGB332 palette MODE 3 640 x 360 x 16 colours with optional layer and colour mapping to RGB332 palette MODE 5 320 x 180 x 256 colours with optional layer (no memory usage) OPTION RESOLUTION 1024 x 768 MODE 1 1024 x 768 x 2 colours with RGB332 tiles (use the TILE command as normal) MODE 2 256 x 192 x 16 colours with 2 optional layers and colour mapping to RGB332 palette MODE 3 512 x 384 x 16 colours with optional layer and colour mapping to RGB332 palette MODE 5 256 x 192 x 256 colours with optional layer,
Page 136
PicoMite User Manual
MOUSE
For all variants of the command. In the case of USB firmware ‘channel’ is the USB port that the mouse is connected to (1-4). See MM.INFO(USB n) for more information. For PS2 firmware ‘channel’ is fixed at the value 2
MOUSE INTERRUPT ENABLE channel, int
'int' is a user defined subroutine that will be called when the left mouse button is pressed.
MOUSE INTERRUPT DISABLE channel
Disables an interrupt on the left mouse button
MOUSE SET channel, ycoord, y-coord [, wheel-count]
Sets the current position that will be returned by the mouse x, y and optionally wheel positions
MOUSE OPEN channel, CLKpin, DATApin
NON USB VERSIONS - ONLY FOR A PS2 MOUSE Opens a connection to a PS2 mouse connected to the two specified pins. This command can be used in a program to configure the mouse while the program is running as against OPTION MOUSE which permanently configures the mouse. Channel is included for compatibility with USB mouse functionality and must be set to 2. If a mouse is not connected you will get an error and the command can be called again once the mouse is connected
MOUSE CLOSE channel
Closes access to the mouse and restores the pins to normal use. The command will error if OPTION MOUSE has been set.
NEW
Clears the program memory and all variables including saved 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 ERROR ABORT or ON ERROR IGNORE or ON ERROR SKIP [nn] or ON ERROR CLEAR
This controls the action taken if an error occurs while running a program and applies to all errors discovered by MMBasic including syntax errors, wrong data, missing hardware, etc. ON ERROR ABORT will cause MMBasic to display an error message, abort the program and return to the command prompt. This is the normal behaviour and is the default when a program starts running. ON ERROR IGNORE will cause any error to be ignored. ON ERROR SKIP will ignore an error in a number of commands (specified by the number 'nn') executed following this command. 'nn' is optional, the default if not specified is one. After the number of commands has completed (with an error or not) the behaviour of MMBasic will revert to ON ERROR ABORT. If an error occurs and is ignored/skipped the read only variable MM.ERRNO will be set to non zero and MM.ERRMSG$ will be set to the error message that would normally be generated. These are reset to zero and an empty string by ON ERROR CLEAR. They are also cleared when the program is run and when ON ERROR IGNORE and ON ERROR SKIP are used. ON ERROR IGNORE can make it very difficult to debug a program so it is strongly recommended that only ON ERROR SKIP be used.
ON KEY target or ON KEY ASCIIcode, target
The first version of the command sets an interrupt which will call 'target' user defined subroutine whenever there is one or more characters waiting in the serial console input buffer.
PicoMite User Manual
Page 137
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. The second version allows you to associate an interrupt routine with a specific key press. This operates at a low level for the serial console and if activated the key does not get put into the input buffer but merely triggers the interrupt. It uses a separate interrupt from the simple ON KEY command so can be used at the same time if required. In both variants, to disable the interrupt use numeric zero for the target, i.e.: ON KEY 0. or ON KEY ASCIIcode, 0 ON PS2 target
This triggers an interrupt whenever the PicoMite firmware sees a message from the PS2 interface. Use MM.info(PS2) to report the raw message received. This allows the programmer to trap both keypress and release. See https://wiki.osdev.org/PS/2_Keyboard for the scan codes (Set 2).
ONEWIRE RESET pin or ONEWIRE WRITE pin, flag, length, data [, data…] or ONEWIRE READ pin, flag, length, data [, data…]
Commands for communicating with 1-Wire devices. ONEWIRE RESET will reset the 1-Wire bus ONEWIRE WRITE will send a number of bytes ONEWIRE READ will read a number of bytes 'pin' is the I/O pin (located in the rear connector) to use. It can be any pin capable of digital I/O. 'flag' is 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' is the length of data to send or receive 'data' is the data to send or variable to receive. The number of data items must agree with the length parameter. See also Appendix C.
OPEN fname$ FOR mode AS [#]fnbr
Opens a file for reading or writing. ‘fname’ is the filename with an optional extension separated by a dot (.). Long file names with upper and lower case characters are supported. The file system on the SD Card is NOT case sensitive however the Flash Filesystem IS case sensitive. A directory path can be specified with the backslash as directory separators. The parent of the current directory can be specified by using a directory name of “..” (two dots) and the current directory with “.” (a single dot). For example: OPEN ".\dir1\dir2\filename.txt" FOR INPUT AS #1 ‘mode’ is INPUT, OUTPUT, APPEND or RANDOM. INPUT will open the file for reading and throw an error if the file does not exist. OUTPUT will open the file for writing and will automatically overwrite any existing file with the same name. APPEND will also open the file for writing but it will not overwrite an existing file; instead any writes will be appended to the end of the file. If there is no existing file the APPEND mode will act the same as the OUTPUT mode (i.e. the file is created then opened for writing). RANDOM will open the file for both read and write and will allow random access using the SEEK command. When opened the read/write pointer is positioned at the end of the file. If the file does not exist , it will be created.
Page 138
PicoMite User Manual
‘fnbr’ is the file number (1 to 10). The # is optional. Up to 10 files can be open simultaneously and can be on either or both the A: and C: drives. The INPUT, LINE INPUT, PRINT, WRITE and CLOSE commands as well as the EOF() and INPUT$() functions all use ‘fnbr’ to identify the file being operated on. See also ON ERROR and MM.ERRNO for error handling. 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.
OPEN comspec$ AS GPS [,timezone_offset] [,monitor]
Will open a serial communications port for reading from a GPS receiver. See the GPS function for details. The sentences interpreted are GPRMC, GNRMC, GPGGA and GNGGA. The timezone_offset parameter is used to convert UTC as received from the GPS to the local timezone. If omitted the timezone will default to UTC. The timezone_offset can be a any number between -12 and 14 allowing the time to be set correctly even for the Chatham Islands in New Zealand (UTC +12:45). If the monitor parameter is set to 1 then all GPS input is directed to the console. This can be stopped by closing the GPS channel.
OPTION
See the section Options earlier in this manual.
PAUSE delay
Halt execution of the running program for ‘delay’ ms. This can be a fraction. For example, 0.2 is equal to 200 µs. The maximum delay is 2147483647 ms (about 24 days). Note that interrupts will be recognised and processed 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 chapter Using the I/O pins for a general description of the PicoMite firmware's input/output capabilities.
PIO
The processors chip in the Raspberry Pi Pico with the RP2040 processors contains a programmable I/O system with two identical PIO devices (pio%=0 or pio%=1) acting like specialised CPU cores. The Raspberry Pi Pico 2 with the RP2350 processors has three PIO devices. See the Appendix F for a more detailed description of programming PIOs.
PIO assemble pio,linedata$
This command will assemble and load text based PIO assembler code including labels for jumps. Use: PIO assemble pio,".program anything" to initialise the assembler. Use: PIO assemble pio,".side_set n [opt] [pindirs]" if using side set. This is mandatory in order to correctly construct the op-codes if one or more side set pins are used. It does not load the pinctrl register as this is specific to the state-machine. Also note the "opt" parameter changes the op-code on instructions that have a side parameter. Use: PIO assemble pio,".line n" to assemble starting from a line other than 1 this is optional.
PicoMite User Manual
Page 139
Use: PIO assemble pio,".end program [list]" to terminate the assembly and program the pio. The optional parameter LIST causes a hex dump of the opcodes to the terminal. Use: PIO assemble pio,"label:" to define a label. This must appear as a separate command. Use: PIO assemble “’.wrap target” to specify where the program will wrap to. See PIO(.wrap target) for how to use this. Use: PIO assemble “.wrap” to specify where the program should wrap back to from “.wrap target” . See PIO(.wrap) for how to use this. Use: PIO assemble pio "instruction [parameters]" to define the actual PIO instructions that will be converted to machine code. PIO DMA RX pio, sm, nbr, data%() [,completioninterrupt] [,transfersize] [,loopbackcount] PIO DMA TX pio, sm, nbr, data%() [,completioninterrupt] [,transfersize] [,loopbackcount]
Sets up DMA transfers from PIO to MMBasic memory. pio specifies which of the two pio instances to use (0 or 1). sm specifies which of the state machine to use (0-3). nbr specifies how many 32-bit words to transfer. See below for the special case of setting nbr to zero. data%() is the array that will either supply or receive the PIO data. The optional parameter completioninterrupt is the name of a MMBasic subroutine rthat will be called when the DMA completes and in the case of DMA_OUT the FIFO has been emptied. If the optional interrupt is not used then the status of the DMA can be checked using the functions: MM.INFO(PIO RX DMA) MM.INFO(PIO TX DMA) The optional parameter transfersize allows the user to override the normal 32bit transfers and select 8, 16, or 32. The optional parameter loopbackcount specifies how many data items are to be read or written before the DMA starts again at the beginning of the buffer. The parameter must be a power of 2 between 2 and 32768. Due to a limitation in the RP2040/RP2350 if loopbackcount is used the MMBasic array must be aligned in memory to the number of bytes in the loop. Thus if the array is 64 integers long which is 512 bytes then the array must be aligned to a 512byte boundary in memory. All MMBasic arrays are aligned to a 256 byte boundary but to create an array which is guaranteed to be aligned to a 512 byte boundary or greater the PIO MAKE RING BUFFER command must be used. If loopbackcount is set then “nbr” can be set to 0. In this case the transfer will run continuously repeatedly filling the buffer until explicitly stopped.
PIO DMA RX OFF PIO DMA TX OFF
Aborts a running DMA.
PIO INTERRUPT pio, sm [,RXinterrupt] [,TXinterrupt]
Sets Basic interrupts for PIO activity. Use the value 0 for RXinterrupt or TXinterrupt to disable an interrupt. Omit values not needed. The RX interrupt triggers whenever a word has been "pushed" by the PIO code into the specified FIFO. The data MUST be read in the interrupt to clear it. The TX interrupt triggers whenever the specified FIFO has been FULL and the PIO code has now "pulled" it
Page 140
PicoMite User Manual
PIO INIT MACHINE pio%, statemachine%, clockspeed [,pinctrl] [,execctrl] [,shiftctrl] [,startinstruction] [,sideout [,setout] [,outout]
Initialises PIO 'pio%' with state machine 'statemachine%'. 'clockspeed' is the clock speed of the state machine in kHz. The first four optional arguments are variables holding initialising values of the state machine registers and the address of the first instruction to execute (defaults to zero). These decide how the PIO will operate. sideout, setout, and outout can be set to 0 (default) or 1 to specify if pins defined in pinctrl should be initialised as inputs (0) or outputs (1)
PIO EXECUTE pio, state_machine, instruction%
Immediately executes the instruction on the pio and state machine specified.
PIO WRITE pio, state_machine, count, data0 [,data1..]
Writes the data elements to the pio and state machine specified. The write is blocking so the state machine needs to be able to take the data supplied NB: this command will probably need additional capability in future releases
PIO WRITEFIFO a,b,v,d
Writes to one of the 4 individual FIFO registers. ‘a’ is the pio (0 or 1), ‘b’ id the state machine (0...3), ‘c’ is the FIFO register *0…3), ‘d’ is the data% (32 bit integer value).
PIO READ pio, state_machine, count, data%[()]
Reads the data elements from the pio and state machine specified. The read is non-blocking so the state machine needs to be able to supply the data requested. When count is one then an integer can be used to receive the data, otherwise and integer array should be specified. NB: this command will probably need additional capability in future releases.
PIO START pio, statemachine
Start a given state machine on pio.
PIO STOP pio, statemachine
Stop a given state machine on pio.
PIO CLEAR pio
This stops the pio specified on all statemachines and clears the control registers for the statemachines PINCTRL, EXECTRL, and SHIFTCTRL to defaults.
PIO PROGRAM pio,array%()
Programs the entire pio program memory with the data in array%(). See Appendix F.
PIO PROGRAM LINE pio, line, instruction
Programs just the specified line in a PIO program.
PIO SET BASE 0/16
PIO commands can only work with 32 GPIO ports. For the RP2350B this command tells the system to use GP0-GP31 (0) or GP16-GP47 (16)
PIO CONFIGURE pio, sm, clock [,startaddress] [,sidesetbase] [,sidesetno] [,sidesetout] [,setbase] [,setno] [,setout] [,outbase] [,outno] [,outout] [,inbase] [,jmppin] [,wraptarget] [,wrap] [,sideenable] [,sidepindir] [,pushthreshold] [,pullthreshold] [,autopush] [,autopull] [,inshiftdir] [,outshiftdir] [,joinrxfifo] [,jointxfifo] [,joinrxfifoget] [,joinrxfifoput]
The parameters in this command are essentially the same as you would use in the PIO INIT command plus the helper functions PINCTRL, SHIFTCTRL and EXECCTRL but combined into a single command. This is required because the Pico sdk does some very clever processing behind the scenes to handle the RP2350B
PicoMite User Manual
‘sidesetbase’, ‘sidebase outbase’, ‘inbase’ and ‘jmppin’ are pin definitions. You can specify these as either a GPno or a pin number (e.g. GP3 or 5). In all cases specify the actual pin. So if PIO SET BASE is set to 16 for that PIO then values GP16 to GP47 are valid. If PIO SET BASE is not set or is set to 0 then pins GP0 to GP31 are valid. They all default to the base set except ‘jmppin’ (defaults to -1) which needs to be explicitly set if you want to use a ‘jmppin’ as this triggers setting the required status bit ‘clock’ is the desired PIO clock speed in Hz
Page 141
‘startaddress’ is the PIO statement that will start execution - defaults to 0 ‘sidesetno’, ‘setno’ and ‘outno’ specify the number of pins that can be used for those functions - default to 0 ‘sidesetout’, ‘setout’ and ‘outout’ specify if those pins should be configured as outputs (1=yes, 0=no) - default to 0 ‘wraptarget and ‘wrap’ are in the range 0-31 and default to 0 and 31 ‘inshiftdir’ and ‘outshiftdir’ default to 1 - shift out of output shift register to right and shift input shift register to right (data enters from left). All other parameters are booleans that can enable a specific function - 1 to enable 0 to disable - all default to 0. Simple example: 'PIO Configure pio, sm, clock, startaddress, 'sidesetbase, sidesetno, sidesetout, 'setbase, setno, setout, outbase, outno, outout, inbase, 'jmppin, wraptarget, wrap, sideenable, sidepindir, 'pushthreshold, pullthreshold, autopush, autopull, inshiftdir, outshiftdir, 'joinrxfifo, jointxfifo, joinrxfifoget, joinrxfifoput PIO assemble 1 .program test .line 0 .wrap target Set pins,1 Set pins,0 .wrap .end program SetPin gp45,pio1 PIO set base 1,16 PIO configure 1,0,1000000,,,,,gp45,1,1,,,,,,Pio(.wrap target),Pio(.wrap) PIO start 1,0 Do Loop Although the PIO CONFIGURE command has many parameters, it is very easy to use if you adopt this simple approach: Copy the comment lines in the example into your program. For each parameter substitute your required value or delete the parameter leaving the commas intact. Once all substitutions are done delete any trailing commas Then assuming the line will be too long for the editor delete the CRs one by one starting at the end of the second last line and moving upwards. In this way you will have a valid command that is easy to input and edit. NB: You can also use continuation lines to make the editing easier (see OPTION CONTINUATION LINES)
PIXEL x, y [,c]
Page 142
Set a pixel on a video output or an attached LCD panel to a colour. 'x' is the horizontal coordinate and 'y' is the vertical coordinate of the pixel. 'c' is a 24 bit number specifying the colour. 'c' is optional and if omitted the current foreground colour will be used. All parameters can be expressed as arrays and the software will plot the number of pixels as determined by the dimensions of the smallest array. 'x' and
PicoMite User Manual
'y' must both be arrays or both be single variables /constants otherwise an error will be generated. 'c' can be either an array or a single variable or constant. See the chapter Graphics Commands and Functions for a definition of the colours and graphics coordinates. PLAY
This command will generate a variety of audio outputs. See the OPTION AUDIO command for setting the I/O pins to be used for the output. The audio is a pulse width modulated signal (PWM) so a low pass filter is required to remove the carrier frequency.
PLAY TONE left [, right [, dur] [,interrupt]]]
Generates two separate frequencies on the sound output left and right channels. 'left' and 'right' are the frequencies in Hz to use for the left and right channels. The tone plays in the background (the program will continue running after this command) and 'dur' specifies the number of milliseconds that the tone will sound for. If the duration is not specified the tone will continue until explicitly stopped or the program terminates. 'interrupt' is an optional subroutine which will be called when the play terminates. The frequency can be from 1Hz to 20KHz and is very accurate (it is based on a crystal oscillator). The frequency can be changed at any time by issuing a new PLAY TONE command.
PLAY FLAC file$ [, interrupt]
Will play a FLAC file on the sound output. 'file$' is the FLAC file to play (the extension of .flac will be appended if missing). The sample rate can be up to 48kHz in stereo (96kHz if the Pico is overclocked) The FLAC file is played in the background. 'interrupt' is optional and is the name of a subroutine which will be called when the file has finished playing. If file$ is a directory on the B: drive the Pico will play all of the files in that directory in turn.
PLAY WAV file$ [, interrupt]
Will play a WAV file on the sound output. 'file$' is the WAV file to play (the extension of .wav will be appended if missing). The WAV file must be PCM encoded in mono or stereo with 8 or 16-bit sampling. The sample rate can be up to 48kHz in stereo (96kHz if the Pico is overclocked). The WAV file is played in the background. 'interrupt' is optional and is the name of a subroutine which will be called when the file has finished playing.
PLAY MP3 file$ [, interrupt]
Will play a MP3 file on the sound output (RP2350 ONLY). 'file$' is the MP3file to play (the extension of .mp3 will be appended if missing). The sample rate can be up to 48kHz. The MP3 file is played in the background. 'interrupt' is optional and is the name of a subroutine which will be called when the file has finished playing. If file$ is a directory on the B: drive the Pico will play all of the files in that directory in turn.
PLAY MODFILE file$ [,interrupt]
Will play a MOD file on the sound output. 'file$' is the MOD file to play (the extension of .mod will be appended if missing). The MOD file is played in the background and will play continuously in a loop. If the optional 'interrupt' is specified This will be called when the file has played once through the sequence and playback will then be terminated. This command will preferentially use space in PSRAM if enabled for the file buffer (RP2350 only). In this case a modbuffer does not need to be enabled with the
PicoMite User Manual
Page 143
OPTION command
PLAY MODSAMPLE Samplenum, channel [,volume]
PLAY LOAD SOUND array%()
PLAY SOUND soundno, channelno, type [,frequency] [,volume]
Plays a specific sample in the mod file on the channel specified. The volume is optional and can be between 0 and 64. This command can only be used when there is a mod file already playing and allows sound effects to be output whilst the background music is still playing. Loads a 1024 element array comprising 4096 16-bit values between 0 and 4095. This provides the data for any arbitrary waveform that can be played by the PLAY SOUND command. You can use the MEMORY PACK command to create the arrays from a normal 4096 element integer array. Play a series of sounds simultaneously on the audio output. 'soundno' is the sound number and can be from 1 to 4 allowing for four simultaneous sounds on each channel. 'channelno' specifies the output channel. It can be L (left speaker), R (right speaker), B (both speakers). type' specifies the wave form to be used. It can be S (Sine wave), Q (square wave) , T (triangular wave) , W (saw tooth) , O (Null output), P (periodic noise), N (random noise) or U (user defined using PLAY LOAD SOUND). 'frequency' is the frequency from 1 to 20000 (Hz) and it must be specified except when type is O. In Type U mode, this parameter can also accept decimal values. For example, all of the following will play back the waveform at its original pitch: Sample rate of 4000, frequency = 1 Sample rate of 8000, frequency = 2 Sample rate of 16000, frequency = 4 'volume' is optional and must be between 1 and 25. It defaults to 25 When PLAY SOUND is called all other audio usage will be blocked and will remain blocked until PLAY STOP is called. Output can be stopped temporarily using PLAY PAUSE and PLAY RESUME. Calling SOUND on an already running 'soundno' will immediately replace the previous output. Individual sounds are turned off using type “O” Running 4 sounds simultaneously on both channels of the audio output consumes about 23% of the CPU.
PLAY PAUSE PLAY RESUME PLAY STOP
PLAY PAUSE will temporarily halt the currently playing file or tone. PLAY RESUME will resume playing a sound that was paused. PLAY STOP will terminate the playing of the file or tone. When the program terminates for whatever reason the sound output will also be automatically stopped.
PLAY VOLUME left, right
Will adjust the volume of the audio output. 'left' and 'right' are the levels to use for the left and right channels and can be between 0 and 100 with 100 being the maximum volume. There is a linear relationship between the specified level and the output. The volume defaults to maximum when a program is run.
PLAY NEXT
Stops playback of the current audio file and starts the next one in the directory
PLAY PREVIOUS
Stops playback of the current audio file and starts the previous one in the directory
VS1053 specific PLAY commands PLAY MP3 file$ [, interrupt]
Page 144
Will play a MP3 file on the sound output.
PicoMite User Manual
'file$' is the MP3 file to play (the extension of .mp3 will be appended if missing). The sample rate should be 44100Hz stereo. The MP3 file is played in the background. 'interrupt' is optional and is the name of a subroutine which will be called when the file has finished playing. If file$ is a directory on the B: drive the Pico will play all of the files in that directory in turn. PLAY HALT
This command works when a MP3 file is playing. It stops playback and records the current file position to allow playback to be resumed from the same point. This command is specifically designed to support for mp3 audio books
PLAY CONTINUE track$
Resumes playback of the MP3 track specified. "track$" will be the name of the file that was playing when halted with all file attributes removed eg, PLAY MP3 "B:/mp3/mymp3.mp3" sometime later PLAY HALT later again PLAY CONTINUE "mymp3"
PLAY MIDIFILE file$ [, interrupt]
Will play a MIDI file on the sound output. 'file$' is the MIDI file to play (the extension of .mid will be appended if missing). The MIDI file is played in the background. 'interrupt' is optional and is the name of a subroutine which will be called when the file has finished playing. If file$ is a directory on the B: drive the Pico will play all of the files in that directory in turn.
PLAY MIDI
Initiates the real-time midi mode. In this mode midi instructions can be sent to the VS1053 to select which instruments to play on which channels, turn notes on, and turn them off in real timer
PLAY MIDI CMD cmd%, data1%, data2%
Sends a midi command when in real time midi mode. An example would be to allocate an instrument to a channel. Eg, PLAY MIDI CMD &B11000001,4 ‘set channel 1 to instrument 4
PLAY MIDI TEST n
Plays a MIDI test sequence, n=0 to 3, 0 = normal realtime, the others play note and instrument samples
PLAY NOTE ON channel%, note%, velocity%
Turns on the note on the channel specified when in real time MIDI mode
PLAY NOTE OFF channel%, note% [,velocity%]
Turns off the note on the channel specified when in real time MIDI mode
PLAY STREAM buffer%(), readpointer%, writepointer%
Sends data to the VS1053 CODEC from the circular buffer “buffer%”. This command initiates a background output stream where the VS1053 is sent anything in the buffer between the readpointer and the write pointer, updating the readpointer as it goes. Can be used for arbitrary waveform output.
POKE BYTE addr%, byte or POKE SHORT addr%, short% or POKE WORD addr%, word%
PicoMite User Manual
Will set a byte or a word within the virtual memory space. Where more than one byte is written the address must be exactly divisible by the number of bytes: 2, 4, or 8 otherwise an error will be reported. POKE BYTE will set the byte (i.e. 8 bits) at the memory location 'addr%' to 'byte'. 'addr%' should be an integer. POKE SHORT will set the short integer (i.e. 16 bits) at the memory location 'addr%' to 'word%'. 'addr%' and short%' should be integers.
Page 145
or POKE INTEGER addr%, int% or POKE FLOAT addr%, float! or POKE VAR var, offset, byte or POKE VARTBL, offset, byte
or POKE DISPLAY command [,data1] [,data2] [,datan]
POKE DISPLAY HRES n POKE DISPLAY VRES n POLYGON n, xarray%(), yarray%() [, bordercolour] [, fillcolour] POLYGON n(), xarray%(), yarray%() [, bordercolour()] [, fillcolour()] POLYGON n(), xarray%(), yarray%() [, bordercolour] [, fillcolour]
Page 146
POKE WORD will set the word (i.e. 32 bits) at the memory location 'addr%' to 'word%'. 'addr%' and 'word%' should be integers. POKE INTEGER will set the MMBasic integer (i.e. 64 bits) at the memory location 'addr%' to int%'. 'addr%' and int%' should be integers. POKE FLOAT will set the word (i.e. 64 bits) at the memory location 'addr%' to 'float!'. 'addr%' should be an integer and 'float!' a floating point number. 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. This command sends commands and associated data to the display controller for a connected display. This allows the programmer to change parameters of how the display is configured. eg, POKE DISPLAY &H28 will turn off an SSD1963 display and POKE DISPLAY &H29 will turn it back on again. Works for all displays except the ST7790. These commands change the stored value of MM.HRES and MM.VRES allowing the programmer to configure non-standard displays. Draws a filled or outline polygon with ‘n’ xy-coordinate pairs in ‘xarray%()’ and ‘yarray%()’. If ‘fillcolour’ is omitted then just the polygon outline is drawn. If ‘bordercolour’ is omitted then it will default to the current default foreground colour. If the last xy-coordinate pair is not the same as the first the firmware will automatically create an additional xy-coordinate pair to complete the polygon. The size of the arrays should be at least as big as the number of x,y coordinate pairs. 'n' can be an array and the colours can also optionally be arrays as follows: POLYGON n(), xarray%(), yarray%() [, bordercolour()] [, fillcolour()] POLYGON n(), xarray%(), yarray%() [, bordercolour] [, fillcolour] The elements of ‘array n()’ define the number of xy-coordinate pairs in each of the polygons. eg, DIM n(1)=(3,3) would define that 2 polygons are to be drawn with three vertices each. The size of the n array determines the number of polygons that will be drawn unless an element is found with the value zero in which case the firmware only processes polygons up to that point. The x,ycoordinate pairs for all the polygons are stored in ‘xarray%()’ and ‘yarray%()’. The ‘xarray%()’ and ‘yarray%()’ parameters must have at least as many elements as the total of the values in the n array. Each polygon can be closed with the first and last elements the same. If the last element is not the same as the first the firmware will automatically create an additional x,y-coordinate pair to complete the polygon. If fill colour is omitted then just the polygon outlines are drawn. The colour parameters can be a single value in which case all polygons are drawn in the same colour or they can be arrays with the same cardinality as ‘n’. In this case each polygon drawn can have a different colour of both border and/or fill. For example, this will draw 3 triangles in yellow, green and red: DIM c%(2)=(3,3,3) DIM x%(8)=(100,50,150,100,50,150,100,50,150) DIM y%(8)=(50,100,100,150,200,200,250,300,300) DIM fc%(2)=(rgb(yellow),rgb(green),rgb(red)) POLYGON c%(),x%(),y%(),fc%(),fc%()
PicoMite User Manual
PORT(start, nbr [,start, nbr]…) = value
Set a number of I/O pins simultaneously (i.e. 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. For example; PORT(15, 4, 23, 4) = &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 the number of I/O pins on the chip. See the PORT function to simultaneously read from a number of pins.
PRINT expression [[,; ]expression] … etc
Outputs text to the serial console followed by a carriage return/newline pair. Multiple expressions can be used and must be separated by either a: Comma (,) which will output the tab character Semicolon (;) which will not output anything (it is just used to separate expressions). Nothing or a space which will act the same as a semicolon. A semicolon (;) or a comma (,) at the end of the expression list will suppress the output of the carriage return/newline pair 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 or small floating point numbers are automatically printed in scientific number format. The function TAB() can be used to space to a certain column and the STR$() function can be used to justify or otherwise format strings.
PRINT #nbr, expression [[,; ]expression] … etc
Same as above except that the output is directed to a serial communications port or a file opened for OUTPUT or APPEND with a file number of ‘nbr’. See the OPEN command.
PRINT #GPS, expression [[,; ]expression] … etc
Outputs a NMEA string to an opened GPS device. The string must start with a $ character and end with a * character. The checksum is automatically calculated and appended to the string together with the CR/LF characters.
PRINT @(x [, y]) expression or PRINT @(x, [y], m) expression
Works on terminal console on an attached computer or VGA/HDMI video or the display if OPTION LCDPANEL CONSOLE is enabled. Same as the standard PRINT command except that the cursor is positioned at the coordinates x, y expressed in pixels. If y is omitted the cursor will be positioned at “x” on the current line. Example: PRINT @(150, 45) "Hello World" The @ function can be used anywhere in a print command. Example: PRINT @(150, 45) "Hello" @(150, 55) "World" The @(x,y) function can be used to position the cursor anywhere on or off the screen. For example, PRINT @(-10, 0) "Hello" will only show "llo" as the first two characters could not be shown because they were off the screen. The @(x,y) function will automatically suppress the automatic line wrap normally performed when the cursor goes beyond the right screen margin. If 'm' is specified the mode of the video operation will be as follows: m = 0 Normal text (white letters, black background) m = 1 The background will not be drawn (ie, transparent)
PicoMite User Manual
Page 147
m = 2 The video will be inverted (black letters, white background) m = 5 Current pixels will be inverted (transparent background) PULSE pin, width
Will generate a pulse on 'pin' with duration of 'width' ms. 'width' can be a fraction. For example, 0.01 is equal to 10µs and this enables the generation of very narrow pulses. The generated pulse is of the opposite polarity to the state of the I/O pin when the command is executed. For example, if the output is set high the PULSE command will generate a negative going pulse. Notes: 'pin' must be configured as an output. For a pulse of less than 3 ms the accuracy is ± 1 µs. For a pulse of 3 ms or more the accuracy is ± 0.5 ms. A pulse of 3 ms or more will run in the background. Up to five different and concurrent pulses can be running in the background and each can have its time changed by issuing a new PULSE command or it can be terminated by issuing a PULSE command with zero for 'width'.
PWM channel, frequency, [dutyA] [,dutyB][,phase][,defer]
There are 8 separate PWM frequencies available (channels 0 to 7) and up to 16 outputs with individually controlled duty cycle. You can output on either PWMnA or PWMnB or both for each channel - no restriction. Duty cycles are specified as a percentage and you can use a negative value to invert the output (-100.0 <= duty <=100.0). To use just channel B use the syntax: ‘PWM channel, frequency, , dutyB’ note the double comma before the required duty cycle. Minimum frequency = (cpuspeed + 1) / (2^24) Hz. Maximum speed is OPTION CPUSPEED/4. At very fast speeds the duty cycles will be increasingly limited. Phase is a parameter that causes the waveforms to be centred such that a wave form with a shorter duty cycle starts and ends equal times from a longer one. Use 1 to enable this mode and 0 (or omit) to run as normal The parameter ‘deferredstart’ when set to 1 configures the PWM channels as but does not start the output running. They can the be started using the PWM SYNC command. This can be used to avoid any undesirable startup artefacts The PWM command is also capable of driving servos as follows: PWM 1,50,(position_as_a_percentage * 0.05 + 5)
PWM SYNC s0 [,s1][,s2][,s3][,s4][,s5][,s6][,s7 ]
This initiates the PWM on channels where a deferred start was defined or just syncs existing running channels. However, the power comes in the ability to offset the channels one to another (defined as a percentage of the time period as per the duty cycle - can be a float) You can use an offset of -1 to omit a channel from the synch
PWM channel, OFF
Stop output on ‘channel’.
RAM
RP2350 with PSRAM enabled only The RAM command allows access to up to 5 RAM program slots (similar to flash slots). RAM slots survive a H/W and software reset but not a power cycle.
RAM LIST
Displays a list of all ram locations including the first line of the program.
RAM LIST n [,all]
List the program saved to slot n. Use ALL to list without page breaks.
RAM ERASE n
Erase a ram program location.
Page 148
PicoMite User Manual
RAM ERASE ALL
Erase all ram program locations.
RAM SAVE n
Save the current program to the ram location specified.
RAM LOAD n
Load a program from the specified ram location into program memory.
RAM RUN n
Runs the program in ram location n, clear all variables. Does not change the program memory.
RAM CHAIN n
Runs the program in ram location n, leaving all variables intact (allows for a program that is much bigger than the program memory). Does not change the program memory. NB: if the chained program uses the READ command it must call RESTORE before the first read.
RAM OVERWRITE n
Erase a ram program location and then save the current program to the ram location specified.
RAM FILE LOAD n, fname$ [,O[VERWRITE]]
Loads the MMBasic file fname$ into the ram slot specified. If the optional parameter OVERWRITE (or O) is specified the content of the flash slot will be overwritten without an error being raised.
RANDOMIZE nbr
Seed the random number generator with ‘nbr’. On the RP2040 the random number generator is seeded with zero at power up and will generate the same sequence of random numbers each time. To generate a different random sequence each time you must use a different value for ‘nbr’ (the TIMER function is handy for that). This command does nothing on the RP2350 which has a hardware random generator that does not require seeding.
RBOX x, y, w, h [, r] [,c] [,fill]
Draws a box with rounded corners on the video output or attached LCD panel starting at 'x' and 'y' which is 'w' pixels wide and 'h' pixels high. 'r' 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. All parameters can be expressed as arrays and the software will plot the number of boxes as determined by the dimensions of the smallest array. 'x', 'y', 'w', and 'h' must all be arrays or all be single variables /constants otherwise an error will be generated. 'r', 'c', and 'fill' can be either arrays or single variables/constants. See the chapter Graphics Commands and Functions 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 in a READ statement must match the data types in DATA statements as they are read. Arrays can be used as variables (specified with empty brackets, eg, a()) and in that case the size of the array is used to determine how many elements are to be read. If the array is multidimensional then the leftmost dimension will be the fastest moving. See also DATA and RESTORE.
READ SAVE or READ RESTORE
READ SAVE will save the virtual pointer used by the READ command to point to the next DATA to be read. READ RESTORE will restore the pointer that was previously saved.
PicoMite User Manual
Page 149
This enables subroutines to READ data and then restore the read pointer so as not to disturb other parts of the program that may be reading the same data statements. These commands can be nested. REFRESH
Initiates an update of the screen for e-ink black and white displays. These can only be updated a full screen at a time and if OPTION AUTOREFRESH is OFF this command can be used to trigger the write. This command works with the following displays: N5110, SSD1306I2C, SSD1306I2C32, SSD1306SPI, ST7920.
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.
RENAME old$ AS new$
Rename a file or a directory from ‘old$’ to ‘new$’. Both are strings. A directory path can be used in both 'old$' and 'new$'. If the paths differ the file specified in 'old$' will be moved to the path specified in 'new$' with the file name as specified.
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 a label or a variable with these values. If ‘line’ is not specified the counters will be reset to the start of the program.
RMDIR dir$
Remove, or delete, the directory ‘dir$’ on the default Flash Filesystem or SD Card.
RTC GETTIME
RTC GETTIME will get the current date/time from a PCF8563, DS1307 or DS3231 real time clock and set the internal MMBasic clock accordingly. The date/time can then be retrieved with the DATE$ and TIME$ functions.
RTC SETTIME year, month, day, hour, minute, second
RTC SETTIME will set the time in the clock chip. 'hour' must use 24 hour notation. ‘year’ can be two or four digits. The RTC SETTIME command will also accept a single string argument in the format of dd/mm/yy hh:mm. This means the date/time could be entered by the user using a GUI FORMATBOX with the DATETIME2 format (see Advanced Graphics Functions.pdf).
RTC SETREG reg, value RTC GETREG reg, var
The RTC SETREG and GETREG commands can be used to set or read the contents of registers within the real time clock chip. 'reg' is the register's number, 'value' is the number to store in the register and 'var' is a variable that will receive the number read from the register. These commands are not necessary for normal operation but they can be used to manipulate special features of the chip (alarms, output signals, etc). They are also useful for storing temporary information in the chip's battery backed RAM. These chips are I2C devices and must be connected to the two I2C pins as specified by OPTION SYSTEM I2C with appropriate pullup resistors. Also see the command OPTION RTC AUTO ENABLE.
RUN or RUN [file$] [, cmdline$]
Run a program. If ‘file$’ is not supplied then run the program currently held in program memory. If ‘file$’ is supplied then run the named file from the Flash or SD Card filesystem. If ‘file$’ does not contain a '.BAS' extension then one will be automatically added. If ‘cmdline$’ is supplied then pass its value to the MM.CMDLINE$ constant of the program when it runs. If ‘cmdline’$ is not supplied then an empty string value is passed to MM.CMDLINE$.. Notes:
Page 150
PicoMite User Manual
• •
Both ‘file$’ and ‘cmdline$’ may be supplied as string expressions. Use FLASH RUN n to run a program stored in a Flash Slot.
SAVE file$
Saves the program in the current working directory of the Flash Filesystem or SD Card as ‘file$’. Example: SAVE “TEST.BAS” If an extension is not specified “.BAS” will be added to the file name. See also FLASH SAVE n for saving to a Flash Slot.
SAVE CONTEXT [CLEAR]
Saves the variable space and optionally clears it - command should be used in top level program and not from within a subroutine. This saves the entire variable space to the A: drive. The command will fail if there is not enough free space on the A: drive. In the case of and RP2350 with PSRAM the variable space will be saved to a reserved area in the PSRAM and the A: drive is not used. See also LOAD CONTEXT
SAVE IMAGE file$ [,x, y, w, h] or SAVE COMPRESSED IMAGE file$ [,x, y, w, h]
Save the current image on the video output or LCD panel as a BMP file. Any LCD panel must be capable of being read, for example, a ILI9341 based panel or a VIRTUAL_M or VIRTUAL_C panel. 'file$' is the name of the file. If an extension is not specified “.BMP” will be added to the file name. The image is saved as a true colour 24-bit image. ‘x’, ‘y’, ‘w’ and ‘h’ are optional and are the coordinates (‘x’ and ‘y’ are the top left coordinate) and dimensions (width and height) of the area to be saved. If not specified, the whole screen will be saved. Note that ‘width’, if used, must be a multiple of 2. SAVE COMPRESSED IMAGE will work the same except that RLE compression will be used to reduce the file size..
SAVE PERSISTENT n%
Saves the value n% in a special memory location that will survive a watchdog reset or a physical reset but not a power cycle See also MM.PERSISTENT or MM.INFO(PERSISTENT)
SEEK [#]fnbr, pos
Will position the read/write pointer in a file that has been opened on the Flash Filesystem or SD Card for RANDOM access to the 'pos' byte. The first byte in a file is numbered one so SEEK #5,1 will position the read/write pointer to the start of the file opened as #5.
SELECT CASE value
CASE testexp [[, testexp] …]
Executes one of several groups of statements, depending on the value of an
expression. 'value' is the expression to be tested. It can be a number or string
variable or a complex expression.
'testexp' (or test-n) is the value that is to be compared against. It can be:
A single expression (i.e. 34, "string" or PIN(4)*5) to which it may equal
A range of values in the form of two single expressions separated by the
keyword "TO" (i.e. 5 TO 9 or "aa" TO "cc")
A comparison starting with the keyword "IS" (which is optional). For
example: IS > 5, IS <= 10.
When a number of test expressions (separated by commas) are used the CASE
statement will be true if any one of these tests evaluates to true.
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
PicoMite User Manual
Page 151
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. Example: SELECT CASE nbr% CASE 4, 9, 22, 33 TO 88 statements CASE IS < 4, IS > 88, 5 TO 8 statements CASE ELSE statements 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 statements. SERVO channel [positionA] [,positionB]
Control a standard servo. ‘positionA’ and ‘positionB’ can be between -120 and 120 and will generate a 50Hz signal between 800uSec and 2.2mSec As with the PWM command the pins must be set up with SETPIN n,PWM To use just channel B use the syntax: SERVO channel,,positionB Refer to the pinout to give the channel and sub-channel (A or B) for each pin
SETPIN pin, cfg [, option]
Will configure an external I/O pin. Refer to the chapter Using the I/O pins for a general description of the Pico'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 (i.e. measure the voltage on the input). ARAW Fast analog input returning a value between 0 and 4095. DIN Digital input If 'option' is omitted the input will be high impedance If 'option' is the keyword "PULLUP" or “PULLDOWN” a constant current of about 50µA will be used to pull the input pin up or down to 3.3V. Due to a bug in the RP2350 chips it is recommended that a pulldown be implemented using a 8.2K or less resistor. FIN Frequency input 'option' can be used to specify the gate time (the length of time used to count the input cycles). It can be any number between 10 ms and 100000 ms. The PIN() function will always return the frequency correctly scaled in Hz regardless of the gate time used. If 'option' is omitted the gate time will be 1 second. The pins can be GP6, GP7, GP8 or GP9 (can be changed with OPTION COUNT). 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. The PIN() function will always return the average period of one cycle correctly scaled in ms regardless of the number of cycles used for the average. If 'option' is omitted the period of just one cycle will be used. The pins can be GP6, GP7, GP8 or GP9 (can be changed with OPTION COUNT). CIN Counting input ‘option’ can be used to specify which edge triggers the count
Page 152
PicoMite User Manual
and if any pullup or pulldown is enabled 2 specifies a falling edge with pullup, 3 specifies that both a falling and rising edge will trigger a count with no pullup applied, 5 specifies both edges but with a pullup applied. If ‘option’ is omitted a rising edge will trigger the count. Due to a bug in the RP2350 chips pulldown is not recommended. The pins can be GP6, GP7, GP8 or GP9 (can be changed with OPTION COUNT). DOUT Digital output 'option' is not used in this mode. The functions PIN() and PORT() can also be used to return the value on one or more output pins. See the function PIN() for reading inputs and the statement PIN()= for setting an output. See the command below if an interrupt is configured. SETPIN pin, cfg, target [, option]
SETPIN GP25, DOUT | HEARTBEAT
SETPIN p1[, p2 [, p3]], device
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 inactive INTH Interrupt on low to high input INTL Interrupt on high to low input INTB Interrupt on both (i.e. 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 commands. 'option' is the same as used in SETPIN pin DIN (above). This mode also configures the pin as a digital input so the value of the pin can always be retrieved using the function PIN(). Refer to the chapter Using the I/O pins for a general description. NOT ON WEBMITE VERSION This version of SETPIN controls the on-board LED. If it is configured as DOUT then it can be switched on and off under program control. If configured as HEARTBEAT then it will flash 1s on, 1s off continually while powered. This is the default state and will be restored to this when the user program stops running. These commands are used for the pin allocation for special devices. Pins must be chosen from the pin designation diagram and must be allocated before the devices can be used. Note that the pins (eg, rx, tx, etc) can be declared in any order and that the pins can be referred to by using their pin number (eg, 1, 2) or GP number (eg, GP0, GP1). Note that on the WebMite version: SPI1 and SPI2 are not available on GP20 to GP28
SETPIN rx, tx, COM1
PicoMite User Manual
COM1 and COM2 are not available on P20 to GP28 I2C is not available on pin 34 (GP28) The following are not available; GP29, GP25, GP24 and GP23
Allocate the pins to be used for serial port COM1. Valid pins are RX: GP1, GP13 or GP17 TX: GP0, GP12, GP16 or GP28
Page 153
SETPIN rx, tx, COM2
Allocate the pins to be used for serial port COM2. Valid pins are RX: GP5, GP9 or GP21 TX: GP4, GP8 or GP20
SETPIN rx, tx, clk, SPI
Allocate the pins to be used for SPI port SPI. Valid pins are RX: GP0, GP4, GP16 or GP20 TX: GP3, GP7 or GP19 CLK: GP2, GP6 or GP18
SETPIN rx, tx, clk, SPI2
Allocate the pins to be used for SPI port SPI2. Valid pins are RX: GP8, GP12 or GP28 TX: GP11, GP15 or GP27 CLK: GP10, GP14 or GP26
SETPIN sda, scl, I2C
Allocate the pins to be used for the I2C port I2C. Valid pins are SDA: GP0, GP4, GP8, GP12, GP16, GP20 or GP28 SCL: GP1, GP5, GP9, GP13, GP17 or GP21
SETPIN sda, scl, I2C2
Allocate the pins to be used for the I2C port I2C2. Valid pins are SDA: GP2, GP6, GP10, GP14, GP18, GP22 or GP26 SCL: GP3, GP7, GP11, GP15, GP19 or GP27
SETPIN pin, PWM[nx]
Allocate pin to PWMnx 'n' is the PWM number (0 to 7) and 'x' and is the channel (A or B). n and x are optional. The setpin can be changed until the PWM command is issued. At that point the pin becomes locked to PWM until PWMn,OFF is issued.
SETPIN pin, IR
Allocate pins for InfraRed (IR) communications (can be any pin).
SETPIN pin, PIOn
Reserve pin for use by a PIO0, PIO1 or PIO2 (RP2350 only) (see Appendix F for PIO details).
SETPIN GP1, FFIN [,gate]
SETTICK period, target [, nbr]
Page 154
RP2350 ONLY Sets GP1 as a fast frequency input. Inputs up to the CPU speed /2 can be recorded. ‘gate’ can be used to specify the gate time (the length of time used to count the input cycles). It can be any number between 10 ms and 100000 ms. The PIN() function will always return the frequency correctly scaled in Hz regardless of the gate time used. If 'option' is omitted the gate time will be 1 second. The function uses PWM channel 0 to do the counting so it is incompatible with any other use of that PWM channel. This will setup a periodic interrupt (or "tick"). Four tick timers are available ('nbr' is 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 ms (about 24 days). These interrupts can be disabled by setting ‘period’ to zero (i.e. SETTICK 0, 0, 3 will disable tick timer number 3).
PicoMite User Manual
SETTICK PAUSE, target [, nbr] or SETTICK RESUME, target [, nbr]
Pause or resume the specified timer. When paused the interrupt is delayed but the current count is maintained.
SORT array() [,indexarray()] [,flags] [,startposition] [,elementstosort]
This command takes an array of any type (integer, float or string) and sorts it into ascending order in place. It has an optional parameter ‘indexarray%()’. If used this must be an integer array of the same size as the array to be sorted. After the sort this array will contain the original index position of each element in the array being sorted before it was sorted. Any data in the array will be overwritten. This allows connected arrays to be sorted. The ‘flag’ parameter is optional and valid flag values are: bit0: 0 (default if omitted) normal sort - 1 reverse sort bit1: 0 (default) case dependent - 1 sort is case independent (strings only). bit2: 0 (default) normal sort - 1 empty strings go to the end of the array The optional ‘startposition’ defines which element in the array to start the sort. Default is 0 (OPTION BASE 0) or 1 (OPTION BASE 1) The optional ‘elementstosort’ defines how many elements in the array should be sorted. The default is all elements after the ‘startposition’. Any of the optional parameters may be omitted so, for example, to sort just the first 50 elements of an array you could use: SORT array(), , , ,50 Example: The array city$() might contain the names of world cities and can be easily sorted into increasing alphabetical order with the command: SORT city$() The SORT command will work with strings, floats and integers however the array to be sorted must be single dimensioned. Often data is held in multiple arrays, for example, the name of each city might be held in the array city$(), the population held in the array pop%() and the size of the city held in area!(). The same index would refer to the name, population and the area of the city. Sorting and accessing this data is a little more complex but it can be done relatively easily using an optional parameter to the sort command as follows: SORT array(), indexarray%() indexarray%() must be a single dimension integer array of the same size as the array being sorted. Following the sort indexarray%() will contain the corresponding index to the original data before it was sorted. (anything previously in indexarray%() will be overwritten). To access the sorted data you would first copy the array holding the main key to a temporary array and sort that while specifying indexarray%(). After the sort indexarray%() can be used to index the original arrays. For example: DIM city$(100),pop%(100),area!(100),sindex%(100),t$(100) FOR i = 0 to 100 t$(i) = city$(i) ‘ temporary copy of the keys NEXT i SORT t$(), sindex%() ‘ sort the temporary array, FOR i = 0 to 100 k = sindex%(i) ‘ index to the original array PRINT city$(k),pop%(k),area!(k)‘ print in sorted order NEXT i
PicoMite User Manual
Page 155
SPI OPEN speed, mode, bits or SPI READ nbr, array() or SPI WRITE nbr, data1, data2, data3, … etc or SPI WRITE nbr, string$ or SPI WRITE nbr, array() or SPI CLOSE
Communications via an SPI channel. See Appendix D for the details. 'nbr' is the number of data items to send or receive 'data1', 'data2', etc can be float or integer and in the case of WRITE can be a constant or expression. If 'string$' is used 'nbr' characters will be sent. 'array' must be a single dimension float or integer array and 'nbr' elements will be sent or received.
SPI2
The same set of commands as for SPI (above) but applying to the second SPI channel.
SPRITE
VGA AND HDMI VERSIONS ONLY The SPRITE commands are used to manipulate small graphic images on the VGA or HDMI screen and are useful when writing games. Sprites operate in framebuffers in MODEs 2 and 3 only. Sprites are always stored as RGB121 'nibbles' for efficiency The maximum size of a sprite is MM.HRES-1 and MM.VRES-1. See also the BLIT command and SPRITE() functions.
SPRITE CLOSE [#]n
Closes sprite “n” and releases its memory resources allowing the sprite number to be re-used. The command will give an error if other sprites are copied from this one unless they are closed first.
SPRITE CLOSE ALL
Closes all sprites and releases all sprite memory. The screen is not changed
SPRITE COPY [#]n, [#]m, nbr
Makes a copy of sprite “n” to “nbr” of new sprites starting a number “m”. Copied sprites share the same loaded image as the original to save memory
SPRITE HIDE [#]n
Removes sprite n from the display and replaces the stored background. To restore a screen to a previous state sprites should be hidden in the opposite order to which they were written "LIFO"
SPRITE HIDE ALL
Hides all the sprites allowing the background to be manipulated. The following commands cannot be used when all sprites are hidden: SPRITE SHOW (SAFE) SPRITE HIDE (SAFE, ALL) SPRITE SWAP SPRITE MOVE SPRITE SCROLLR SPRITE SCROLL
SPRITE RESTORE
Restores the sprites that were previously hidden with SPRITE HIDE ALL.
SPRITE HIDE SAFE [#]n
Removes sprite n from the display and replaces the stored background. Automatically hides all more recent sprites as well as the requested one and then replaces them afterwards. This ensures that sprites that are covered by other sprites can be removed without the user tracking the write order. Of course this version is less performant than the simple version and should only be used it there is a risk of the sprite being partially covered.
SPRITE INTERRUPT sub
Specifies the name of the subroutine that will be called when a sprite collision occurs. See Appendix H for how to use the function SPRITE to interrogate details of what has collided.
Page 156
PicoMite User Manual
SPRITE READ [#]b, x, y, w, h
This will copy a portion of the display to the memory buffer '#b'. The source coordinate is 'x' and 'y' and the width of the display area to copy is 'w' and the height is 'h'. When this command is used the memory buffer is automatically created and sufficient memory allocated. This buffer can be freed and the memory recovered with the SPRITE CLOSE command.
SPRITE WRITE [#]b, x, y [,mode]
Will copy sprite '#b' to the display. The destination coordinate is 'x' and 'y'. The optional 'mode' parameter defaults to 4 and specifies how the stored image data is changed as it is written out. It is the bitwise AND of the following values: &B001 = mirrored left to right &B010 = mirrored top to bottom &B100 = don't copy transparent pixels
SPRITE LOAD fname$ [,start_sprite_number] [,mode]
Loads the file ‘fname$’ which must be formatted as an original Colour Maximite sprite file. See the original Colour Maximite MMBasic Language Manual for the file format. Multiple sprite files can be loaded by specifying a different ‘start_sprite_number’ for each file. The programmer is responsible for making sure that the sprites do not overlap. Mode defaults to zero in which case the CMM1/CMM2 colour codes are used (Black, Blue, Green, Cyan, Red, Magenta, Yellow, White, Myrtle, Cobalt, Midgreen, Cerulean, Rust, Fuchsia, Brown, Lilac); If mode is specified as 1 then the RGB121 colour codes are used: (Black, Blue, Myrtle, Cobalt, Midgreen, Cerulean, Green, Cyan, Red, Magenta, Rust, Fuchsia, Brown, Lilac, Yellow, White).
SPRITE LOADARRAY [#]n, w, h, array%()
Creates the sprite 'n' with width 'w' and height 'h' by reading w*h RGB888 values from 'array%()'. The RGB888 values must be stored in order of columns across and then rows down starting at the top left. This allows the programmer to create simple sprites in a program without needing to load them from disk or read them from the display. The firmware will generate an error if 'array%()' is not big enough to hold the number of values required.
SPRITE LOADBMP [#]b, fname$ [,x] [,y] [,w] [,h]
Will load a blit buffer from a 24-bit bmp image file. 'x' and 'y' define the start position in the image to start loading and 'w' and 'h' specify the width and height of the area to be loaded. eg, SPRITE LOAD #1,"image1", 50,50,100,100 will load an area of 100 pixels square with the top left had corner at 50, 50 from the image image1.bmp
SPRITE LOADPNG [#]b, fname$ [,transparent] [,alphacut]
Loads SPRITE number ‘b’ from the png file ‘fname$’. If no extension is specified .png will be automatically added to the filename. The file must be in RGBA8888 format which is the normal default. The optional parameter 'transparent' (defaults to 0) specifies one of the colour codes (0-15) which will be allocated to pixels in the png file with an alpha value less than 'alphacut' (defaults to 20). The variable transparency can then used with the command SPRITE SET TRANSPARENT n or FRAMEBUFFER LAYER n to display the sprite with the transparent region hidden.
SPRITE MOVE
Actions a single atomic transaction that re-locates all sprites which have previously had a location change set up using the SPRITE NEXT command. Collisions are detected once all sprites are moved and reported in the same way as from a scroll
SPRITE NEXT [#]n, x, y
Sets the X and Y coordinate of the sprite to be used when the screen is next scrolled or the SPRITE MOVE command is executed. Using SPRITE NEXT rather than SPRITE SHOW allows multiple sprites to be moved as part of the same atomic transaction.
PicoMite User Manual
Page 157
SPRITE SCROLL x, y [,col]
Scrolls the background and any sprites on the active framebuffer (L or N) 'x' pixels to the right and 'y' pixels up. 'x' can be any number between MM.HRES-1 and MM.HRES-1, 'y' can be any number between -MM.VRES-1 and MM.VRES-1. Sprites on any layer other than zero will remain fixed in position on the screen. By default the scroll wraps the image round. If 'col' is specified the colour will replace the area behind the scrolled image. If 'col' is set to -1 the scrolled area will be left untouched.
SPRITE SET TRANSPARENT n
Sets the colour code (0-15) which will be used as transparent when sprites are displayed over a background (defaults to 0).
SPRITE SHOW [#]n, x,y, layer [,options]
Displays sprite ‘n’ on the screen with the top left at coordinates ‘x’, ‘y’. Sprites will only collide with other sprites on the same layer, layer zero, or with the screen edge. If a sprite is already displayed on the screen, then the SPRITE SHOW command acts to move the sprite to the new location. The display background is stored as part of the command and will be replaced when the sprite is hidden or moved further. The parameter ‘options’ is optional and can be set as follows: bit 0 set - mirrored left to right bit 1 set - mirrored top to bottom bit 2 set - black pixels not treated as transparent default is 0
SPRITE SHOW SAFE [#]n, x,y, layer [,orientation] [,ontop]
Shows a sprite and automatically compensates for any other sprites that overlap it. If the sprite is not already being displayed the command acts exactly the same as SPRITE SHOW. If the sprite is already shown it is moved and remains in its position relative to other sprites based on the original order of writing. i.e. if sprite 1 was written before sprite 2 and it is moved to overlap sprite 2 it will display under sprite 2. If the optional "ontop" parameter is set to 1 then the sprite moved will become the newest sprite and will sit on top of any other sprite it overlaps. Refer to SPRITE SHOW for details of the orientation parameter.
SPRITE SWAP [#]n1, [#]n2 [,orientation]
Replaces the sprite ‘n1’ with the sprite ‘n2’. The sprites must have the same width and height and ‘n1’ must be displayed or an error will be generated. Refer to SPRITE SHOW for details of the orientation parameter. The replacement sprite inherits the background from the original as well as its position in the list of order drawn.
STATIC variable [, variables] See DIM for the full syntax.
Defines a list of variable names which are local to the subroutine or function. These variables will retain their value between calls to the subroutine or function (unlike variables created using the LOCAL command). This command uses exactly the same syntax as DIM. The only difference is that the length of the variable name created by STATIC and the length of the subroutine or function name added together cannot exceed 31 characters. Static variables can be initialised to a value. This initialisation will take effect only on the first call to the subroutine (not on subsequent calls).
SUB xxx (arg1 [,arg2, …])
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. i.e. arg3(). The type of the argument can
be specified by using a type suffix (i.e. arg1$) or by specifying the type using
AS
Page 158
PicoMite User Manual
variable and therefore may be accessed after the subroutine has ended. The argument can be prefixed with BYVAL which will prevent this mechanism and cause only the value to be used. Alternatively, the prefix BYREF instructs MMBasic that a reference is required and an error will be generated if that cannot be done. Arrays are passed by specifying the array name with empty brackets (eg, arg()) and are always passed by reference and must be the correct type. 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 a1, 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 and have the correct type will be passed by reference to the subroutine. This means that any changes to the corresponding argument in the subroutine will also be copied to the caller's variable and therefore may be accessed after the subroutine has ended. The argument can be prefixed with BYVAL which will prevent this mechanism and cause only the value to be used. Alternatively, the prefix BYREF instructs MMBasic that a reference must be used and an error will occur if that cannot be done. 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. SYNC time% [,period] or SYNC
The SYNC command allows the user to implement very precisely timed repeated actions (1-2 microseconds accuracy). To enable this the command is first called with the parameter time%. This sets up a repeating clock for time% microseconds. The optional parameter ‘period’ modifies the time and can be “U” for microseconds, “M” for milliseconds or “S” for seconds. Once the clock is set up the program is synchronised to it using the SYNC command without parameters. This waits for the clock period to expire. For periods below 2 ms this is non-interruptible. Above 2 ms the program will respond to Ctrl-C but not any MMBasic interrupts. Typical use is to set the clock outside of a loop and then at the top of the loop call the SYNC command without parameters. This means the contents of the loop will be executed exactly once for each clock period set. For example, the following would drive a servo with the required precise 50Hz timing: SYNC 20, M DO SYNC PULSE GP0,n LOOP
TEMPR START pin [, precision] [,timeout]
This command can be used to start a conversion running on a DS18B20 temperature sensor connected to 'pin'. Normally the TEMPR() function alone is sufficient to make a temperature measurement so usage of this command is optional. For more detail see the section Measuring Temperature.
PicoMite User Manual
Page 159
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 TEMPR() function is used before the conversion time has completed the function will wait for the remaining conversion time before returning the value. Any number of these conversions (on different pins) can be started and be running simultaneously. 'precision' is the resolution of the measurement and is optional. It is a number between 0 and 3 meaning: 0 = 0.5ºC resolution, 100 ms conversion time. 1 = 0.25ºC resolution, 200 ms conversion time (this is the default). 2 = 0.125ºC resolution, 400 ms conversion time. 3 = 0.0625ºC resolution, 800 ms conversion time. The optional timeout parameter overrides the conversion times above to allow for slow devices. TEXT x, y, string$ [,alignment$] [, font] [, scale] [, c] [, bc]
TILE x, y [,foreground] [,background] [,nbr_tiles_wide] [,nbr_tiles_high]
Page 160
Displays a string on the video output or attached LCD panel starting at 'x' and 'y'. ‘string$’ is the string to be displayed. Numeric data should be converted to a string and formatted using the Str$() function. ' alignment$' is a string expression or string variable consisting of 0, 1 or 2 letters where the first letter is the horizontal alignment around 'x' and can be L, C or R for LEFT, CENTER, RIGHT and the second letter is the vertical alignment around 'y' and can be T, M or B for TOP, MIDDLE, BOTTOM. The default alignment is left/top. For example. “CM” will centre the text vertically and horizontally. The 'alignment$' string can be a constant (eg, “CM”) or it can be a string variable. For backwards compatibility with earlier versions of MMBasic the string can also be unquoted (eg, CM). A a third letter can be used in the alignment string to indicate the rotation of the text. This can be 'N' for normal orientation, 'V' for vertical text with each character under the previous running from top to bottom, 'I' the text will be inverted (i.e. upside down), 'U' the text will be rotated counter clockwise by 90º and 'D' the text will be rotated clockwise by 90º '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 chapter Graphics Commands and Functions for a definition of the colours and graphics coordinates. VGA OR HDMI VERSIONS MODE 1 ONLY Sets the colour for one or more tiles on the screen. When in monochrome mode by default the video screen is split up into 80x40 tiles each 8x12 pixels. This matches font 1 and allows full colour coding in the editor in monochrome mode. Each tile can have a different foreground and background named colour assigned to it from the following: white, yellow, lilac, brown, fuchsia, rust, magenta, red, cyan, green, cerulean, midgreen, cobalt, myrtle, blue and black. 'x' and 'y' are the coordinates of the start block (0-79, 0-39) 'foreground ' and 'background' are the new colours selected. 'nbr_tiles_wide' and 'nbr_tiles_high' are the number of tiles to change. The change is instant and does not affect the text or graphics currently displayed in the tiles (just the colours).
PicoMite User Manual
TILE HEIGHT n
Sets the height of the tiles. ‘n’ can be between 12 and 480 (RP2040) or between 8 and 480 (RP2350)
TIME$ = "HH:MM:SS" or TIME$ = "HH:MM" or TIME$ = "HH"
Sets the time of the internal clock. MM and SS are optional and will default to zero if not specified. For example TIME$ = "14:30" will set the clock to 14:30 with zero seconds. With OPTION RTC AUTO ENABLE the PicoMite firmware starts with the TIME$ programmed in RTC. Without OPTION RTC AUTO ENABLE the firmware starts with TIME$="00:00:00"
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 number. See the TIMER function for more details.
TRACE ON or TRACE OFF or TRACE LIST nn
TRACE ON/OFF will turn on/off 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. TRACE LIST will list the last 'nn' lines executed in the format described above. MMBasic is always logging the lines executed so this facility is always available (ie, it does not have to be turned on).
TRIANGLE X1, Y1, X2, Y2, X3, Y3 [, C [, FILL]]
Draws a triangle on the attached video output or LCD display panel with the corners at X1, Y1 and X2, Y2 and X3, Y3. 'C' is the colour of the triangle and defaults to the current foreground colour. 'FILL' is the fill colour and defaults to no fill (it can also be set to -1 for no fill). All parameters can be expressed as arrays and the software will plot the number of triangles as determined by the dimensions of the smallest array unless X1 = Y1 = X2 = Y2 = X3 = Y3 = -1 in which case processing will stop at that point 'x1', 'y1', 'x2', 'y2', 'x3',and 'y3' must all be arrays or all be single variables /constants otherwise an error will be generated 'c' and 'fill' can be either arrays or single variables/constants.
TRIANGLE SAVE [#]n, x1,y1,x2,y2,x3,y3
Saves a triangular area of the screen to buffer #n.
TRIANGLE RESTORE [#]n
Restores a saved triangular region of the screen and deletes the saved buffer.
UPDATE FIRMWARE
NOT ON USB VERSIONS Causes the PicoMite firmware to enter the firmware update mode (the same as applying power while holding down the BOOTSEL button). This command is only available at the command prompt.
VAR SAVE var [, var]… or VAR RESTORE or VAR CLEAR
PicoMite User Manual
VAR SAVE will save one or more variables to non-volatile flash memory where they can be restored later (normally after a power interruption). 'var' can be any number of numeric or string variables and/or arrays. Arrays are specified by using empty brackets. For example: var() The VAR SAVE command can be used repeatedly. Variables that had been previously saved will be updated with their new value and any new variables (not previously saved) will be added to the saved list for later restoration. VAR RESTORE will retrieve the previously saved variables and insert them (and their values) into the variable table. VAR CLEAR will erase all saved variables. 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
Page 161
the program so that previously saved variables are restored and immediately available to the program when it starts. Notes: The storage space available to this command is 16KB. Using VAR RESTORE without a previous save will have no effect and will not generate an error. If, when using RESTORE, a variable with the same name already exists its value will be overwritten. Saved arrays must be declared (using DIM) before they can be restored. Be aware that string arrays can rapidly use up all the memory allocated to this command. The LENGTH qualifier can be used when a string array is declared to reduce the size of the array (see the DIM command). This is not needed for ordinary string variables. The saved variables will be automatically cleared by a firmware upgrade, by the NEW command or when a new program is loaded via AUTOSAVE, XMODEM, etc. WATCHDOG timeout or WATCHDOG OFF or WATCHDOG HW timeout or WATCHDOG HW OFF
Starts the watchdog timer which will automatically restart the processors when it has timed out. This can be used to recover from some event that disabled the running program (such as an endless loop or a programming or other error that halts a running program). This can be important in an unattended control situation. The timeout can either be processed in the system timer interrupt (WATCHDOG command) or as a true CPU/hardware watchdog (WATCHDOG HW command). If the hardware watchdog is used the timer has a maximum of 8.3 seconds. No such limitation exists for the software watchdog. '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 watchdog timer (to ‘timeout’) 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 PicoMite firmware will be automatically restarted and the automatic variable MM.WATCHDOG will be set to true (i.e. 1) indicating that an error occurred. On a normal startup MM.WATCHDOG will be set to false (i.e. 0). Note that OPTION AUTORUN must be specified for the program to restart. 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 (CTRL-C) is used on the console to interrupt a running program.
WII [CLASSIC] OPEN [,interrupt]
Opens a WII Classic controller and implements background polling of the device. The Wii Classic must be wired to the pins specified by OPTION SYSTEM I2C which is a prerequisite. Open attempts to talk to the Wii Classic and will return an error if not found. If found the firmware will sample the Wii data in the background at a rate of 50Hz. If an optional user interrupt is specified this will be triggered if any of the buttons changes (both on and off) See the DEVICE function for how to read data from the Wii Classic.
WII [CLASSIC] CLOSE
CLOSE will stop the background polling and disable any interrupt specified
WII NUNCHUCK OPEN [,interrupt]
Opens a WII Nunchuck controller and implements background polling of the device. The Wii Nunchuck must be wired to the pins specified by OPTION SYSTEM I2C which is a prerequisite. Open attempts to talk to the Wii Nunchuck and will return an error if not found. If found the firmware will sample the Wii data in the background at a
Page 162
PicoMite User Manual
rate of 50Hz. If an optional user interrupt is specified this will be triggered if either of the buttons changes (both on and off) See the DEVICE function for how to read data from the Wii Nunchuck. WII NUNCHUCK CLOSE
CLOSE will stop the background polling and disable any interrupt specified
WEB
WEBMITE ONLY The WEB commands are used to manage the Internet capability of the WebMite.
WEB CONNECT [ssid$, passwd$, [name$] [,ipaddress$, mask$, gateway$]]
This command, with no optional parameters, will connect to the default network if possible (as previously set with OPTION WIFI) or with the optional parameters will connect to the network specified and also set up the OPTION WIFI for future use.
WEB MQTT CONNECT addr$, port, user$, passwd$ [, interrupt]
Connect to an MQTT Broker. 'addr$' is the IP address, 'port' is the port number to use, 'user$' is the user name, 'passwd$' is the account's password and 'interrupt' is optional and if specified is the subroutine to call when a message is received. WEB CONNECT does not disconnect from a previously connected network so should only be used where nothing has been previously set up or where a previously configured network is not active or a previously configured network has failed to connect on boot (no parameters)
WEB MQTT PUBLISH topic$, msg$, [,qos] [,retain]
Publish content to an MQTT broker topic. 'topic$' is the topic name and 'msg$' is the message/ 'qos' is the optional quality of service with values of 0, 1 or 2 (default is 1).
WEB MQTT SUBSCRIBE topic$ [,qos]
Subscribe to an MQTT broker topic. 'topic$' is the topic name and 'qos' is the optional quality of service with values of 0, 1 or 2 (default is 1).
WEB MQTT UNSUBSCRIBE topic$
Unsubscribe from an MQTT broker topic. 'topic$' is the topic name.
WEB MQTT CLOSE
Close a persistent MQTT Connection.
WEB NTP [timeoffset [, NTPserver$]] [,timeout]]]
Get the date/time from an NTP server and set the internal WebMite date/time clock. ' timeoffset' is the local time zone, and if omitted the date/time will be set to GMT. ' NTPserver$' is the timeserver to use and if omitted will default to an international timeserver pool. 'timeout' is the optional time out in milliseconds and defaults to 5000.
WEB OPEN TCP CLIENT address$, port
Opens a TCP client connection to a WEB server. 'address$' is a string and is the address of the server to connect to. It can be either a URL (eg, "api.openweathermap.org") or an IP address (eg, "192.168.1.111"). 'port' is the number of the port to use. Used with WEB TCP CLIENT REQUEST to interrogate the server. Note that one CLIENT connection is allowed.
WEB OPEN TCP STREAM address$, port
Opens a TCP client connection to a WEB server like WEB OPEN TCP CLIENT but connects the WEB TCP CLIENT STREAM receiver logic rather than the logic for WEB TCP CLIENT REQUEST.
PicoMite User Manual
Page 163
'address$' is a string and is the address of the server to connect to. It can be either a URL (eg, "api.openweathermap.org") or an IP address (eg, "192.168.1.111"). 'port' is the number of the port to use. Note that one CLIENT connection is allowed. WEB SCAN [array%()]
Scans for all available wifi connections. If ‘array%()’ is specified the output will be stored in a Longstring, otherwise output will be to the console. The command can be used whether ot not an network connection is already active.
WEB TCP CLIENT REQUEST request$, buff%() [,timeout]
Send a request to the remote server opened with WEB OPEN TCP CLIENT and wait for an answer. 'request$' is a string and is the request to be sent to the server. 'buff%()' is an integer array which will receive the response as a LONGSTRING. The size of this buffer will limit the amount of data received from the server. 'timeout' is the optional time out in milliseconds and defaults to 5000. If the request times out an error will occur, otherwise the received data will be saved in the LONGSTRING 'buff%()'. If the received data is a JSON string then the JSON$() function can be used to parse it.
WEB TCP CLIENT STREAM command$, buffer%(), readpointer%, writepointer%
Connects to a server previously opened with WEB OPEN TCP STREAM. 'command$' is a string and is the request to be sent to the server. 'buffer%()' is an integer array which will receive the ongoing responses and acts as a circular buffer of bytes received. The firmware maintains the parameter ‘writepointer%’ as the data from the server arrives. ‘readpointer%’ should be maintained by the Basic program as it removes data from the circular buffer. If ‘writepointer%’ catches up with ‘readpointer%’ then ‘readpointer%’ will be incremented to stay one byte ahead and incoming data will be lost. This command is designed to be compatible with the PLAY STREAM command to allow the implementation of streaming internet audio.
WEB CLOSE TCP CLIENT
Closes the connection to the remote server opened with WEB OPEN TCP CLIENT. This must be done before another open is attempted.
WEB TCP INTERRUPT InterruptSub
Start the TCP server running. 'InterruptSub' is the subroutine to call when a request is made of the TCP server (ie, an interrupt). Note that the OPTION WIFI command must have been used first followed by the OPTION TCP SERVER PORT command to enable the TCP server.
WEB TCP READ cb%, buff%()
Read the data from a potential TCP connection' cb%'. ' buff%()' is an array to receive any data from that connection as a longstring. The size of this buffer will limit the amount of data received from the remote client. If there is nothing received on that connection this will return an empty string (ie, LLEN(buff%())=0). If there is data that has been received then the BASIC program must respond with one of the WEB TRANSMIT commands in order to respond and close the connection.
WEB TCP SEND cb%, data%() WEB TCP CLOSE cb%
These two commands allow more flexibility in using the TCP server. Unlike WEB TRANSMIT PAGE or WEB TRANSMIT FILE, WEB TCP SEND does not create any sort of header, nor does it close the TCP connection after transmission. It just sends exactly what is in the LONGSTRING data%() and it is up to the Basic programmer to close the connection when appropriate.
Page 164
PicoMite User Manual
WEB TRANSMIT CODE cb%, nnn%
Send a numerical response to the open TCP connection 'cb%' and then closes the connection. Typical use would be TRANSMIT CODE cb%, 404 to indicate page not found.
WEB TRANSMIT FILE cb%, filename$, content-type$
Constructs an HTTP 1.1 header with the ’content-type$’ as specified, sends it and then sends the contents of the file to the open TCP connection cb% and on completion, closes the connection. ’content-type$’ is a MIME type expressed as a string. Eg, "image/jpeg"
WEB TRANSMIT PAGE cb%, filename$ [,buffersize]
Constructs an HTTP 1.1 header, sends it and then sends the contents of the file to the open TCP connection cb% and on completion closes the connection. MMBasic will substitute current values for any MMBasic variables or expressions defined in the file inside curly brackets eg, {myvar%}. Variables can be simple, array elements or expressions. An opening curly bracket can be included in the output by using {{. By default the command allocates a buffer the size of the file + 4096 bytes to build the page to transmit. However, if the page is complex and includes many MMBasic variables that yield text bigger than the variable name it is possible that the buffer will not be big enough. In this case the user can specify the extra space required (defaults to 4096 if not specified)
WEB UDP INTERRUPT intname
Sets up a BASIC interrupt routine that will be triggered whenever a UDP datagram is received. The contents will be saved in MM.MESSAGE$. The IP address of the sender will be stored in MM.ADDRESS$.
WEB UDP SEND addr$, port, data$
Used to send a datagram to a remote receiver. In this case the IP address must be specified and can be either a numeric address (eg, "192.168.1.147") or a normal text address (eg, "google.com"). The port number of the receiver must also be specified and the message itself. The SEND command can be used as a response to an incoming message or stand-alone.
WS2812 type, pin, nbr, value%[()]
This command will drive one or more WS2812 LED chips connected to 'pin'. Note that the pin must be set to a digital output before this command is used. 'type' is a single character specifying the type of chip being driven: O = original WS2812 B = WS2812B S = SK6812 W =SK6812W (RGBW) ‘nbr’ is the number of LEDs in the chain (1 to 256). The 'value%()' array should be an integer array sized to have exactly the same number of elements as the number of LEDs to be driven. For the first three variants each element in the array should contain the colour in the normal RGB888 format (i.e. 0 to &HFFFFFF). For type W use a RGBW value (0-&HFFFFFFFF). If only one LED is connected then a single integer should be used for ‘value%’ (ie, not an array).
XMODEM SEND or XMODEM SEND file$ or XMODEM RECEIVE or
Transfers a BASIC program to or from a remote computer using the XModem protocol. The transfer is done over the USB console connection. XMODEM SEND will send the current program held in the PicoMite's program memory to the remote device. XMODEM RECEIVE will accept a program sent by the remote device and save it into the PicoMite's the program memory overwriting the program currently held there.
PicoMite User Manual
Page 165
XMODEM RECEIVE file$ or XMODEM CRUNCH
Page 166
In both cases you can also specify 'file$' which will transfer the data to/from a file on the Flash Filesystem or SD Card. If the file already exists it will be overwritten when receiving a file. Note that the data is buffered in RAM which limits the maximum transfer size. This command also creates a backup of the program in flash memory which will be automatically retrieved if the CPU is reset of the power is lost. The CRUNCH option works like RECEIVE but will remove all comments, blank lines and unnecessary spaces from the program before saving. This can be used on large programs to allow them to fit into limited memory. SEND, RECEIVE and CRUNCH can be abbreviated to S, R and C. 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 -> Transfer -> XMODEM -> 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/