Ne XT Byte Codes Manual Explanations and Examples

Ne. XT Byte Codes Manual Explanations and Examples of Ne. XT Byte Codes (NBC) By John Hansen & Michael Andersen

What is NBC • Ne. XT Byte Codes – A simple language used to write programs for the standard NXT firmware • Define – aggregate types (structs) • Declare – scalars, arrays, and aggregates – Scalars can be byte, signed byte, word, signed word, dword, and signed dword types – Strings are supported in the form of arrays of byte • Initialize – provide non-zero default values • Execute – use data as arguments for NXT executable code

NBC Sample // My. Simple. Prog. nbc #include "NXTDefs. h" dseg segment ; Define My. Structure. Def struct result sbyte freq word time word loop byte vol byte My. Structure. Def ends ; Declare the. Struct My. Structure. Def var 1 byte TRUE str. Msg byte[] 'Testing' ; Initialize a. Data dword[] 0 x 10, 0 x 20, 0 x 30, 0 x 40, 0 x 50 dseg ends thread main ; Execute Loop: /* loop body goes here */ brtst EQ, Loop, var 1 ; if false loop the. End: exit endt

Sourcecode • Programs have zero or more data segments and a single code segment – If you aren't in a data segment you are in the code segment – The code segment contains one or more threads which comprise the executable program logic • Data segments contain all type definitions and variable declarations – You can have multiple data segments – All variables are global regardless of where they are declared – Example: dseg segment // type definitions and variable declarations go here dseg ends thread main dseg segment // or here dseg ends endt

Preprocessing • • Use standard preprocessor features such as #include, #define, #ifdef, #else, #endif, etc… NBC programs typically begin with #include "NXTDefs. h" – This standard header file includes many important constants and macros which form the core NBC API (application programming interface). • Use #define to define your own constants for use throughout the program – #define Turn. Time 3000 ; 3 seconds • Define powerful multi-line function macros which can replace common chunks of program code – #define My. Macro(x, y, berase, msg) mov dt. Args. Location. X, x mov dt. Args. Location. Y, y mov dt. Args. Options, berase mov dt. Args. Text, msg syscall Draw. Text, dt. Args – My. Macro(0, 0, TRUE, 'testing') My. Macro(10, 20, FALSE, 'Please Work')

Parsing • Comments (EOL = end of line) – ; text to EOL following a semicolon is a comment – // text to EOL following double forward slashes is a comment – /* everything contained within c-style block comment characters is a comment */ • Case – Compiler is case-sensitive; y is not the same identifier as Y • Strings – Delimited by single quote characters. Embedded single quote characters are not supported in the initial NBC release. • Whitespace – Ignored outside of string initializations and constant expressions • Whitespace in a constant expression will result in a compiler error – Required to separate labels, opcodes, and arguments – Required to separate variable names, variable types, and initial values • Multiple arguments are separated by commas

Compiler Tokens • NBC supports special tokens which it replaces on compilation. – Similar to preprocessor #defines but handled directly by the compiler. • Supported tokens – – – – – __FILE__: Replaced with the currently active filename (no path) __LINE__: Replaced with the current line number __VER__: Replaced with the compiler version number __THREADNAME__: Replaced with the current thread name __I__, __J__: Replaced with the current value of I or J. These are both initialized to zero at the start of each thread or subroutine. __Reset. I__, __Reset. J__: Replaced with nothing. As a side effect the value of I or J is reset to zero. __Inc. I__, __Inc. J__: Replaced with nothing. As a side effect the value of I or J is incremented by one. __Dec. I__, __Dec. J__: Replaced with nothing. As a side effect the value of I or J is decremented by one. ##: Replaced with nothing. This token allows you to make the use of other compiler tokens more readable. • __THREADNAME__##_##__I__: would become something like main_1:

Type Definitions • Contained in data segments – Used to define type aliases or aggregate types (struct) • A structure definition – Begins with a type name followed by the keyword "struct" – Ends with the same type name followed by the keyword "ends" – Example: My. Point struct x byte y byte My. Point ends big typedef dword ; big is now an alias for the native dword type Complex. Strut struct value 1 big // using a type alias value 2 sdword buffer byte[] /* array of byte */ blen word extrastuff My. Point[] // array of structs pt_1 My. Point // struct contains struct instances pt_2 My. Point Complex. Struct ends

Type Declarations • Contained in data segments – Used to declare variables for use in the code segment x byte // x = 0 y byte 12 // y = 12 z byte[] 'Testing' // z is an array of byte = (0 x 54, 0 x 65, 0 x 73, 0 x 74, 0 x 69, 0 x 6 e, 0 x 67, 0 x 00) my. Big big 0 x 12345 // use a type alias my. Struct Complex. Struct // declare an instance of a struct – Primary scalar types • byte, sbyte, ubyte – unsigned and signed byte types (8 bits) • word, sword, uword – unsigned and signed word types (16 bits) • dword, sdword, udword – unsigned and signed double word types (32 bits) – long, slong, and ulong are aliases for these double word types – Other scalar types • void – supported by firmware and compiler but not used in executable code • mutex - used for calling a subroutine with exclusive access – Arrays • Declared using type name (scalar or aggregate) followed by [] • Declare arrays of arrays by adding additional [] pairs

Executable Code • Contained in the code segment of an NBC program – Tells the NXT what to do and when to do it – Consists of threads or subroutines containing operations (opcodes) and arguments which are assembled into a series of word (2 byte) values. • Basic unit of program flow is called a thread – – All programs must have at least one thread All threads must be finalized correctly A special type of thread is a subroutine Example: thread main /* body of main thread goes here */ call my. Sub // compiler handles the subroutine return address exit // finalize execution (details are handled by the compiler) endt subroutine my. Sub /* body of subroutine goes here */ return // compiler handles the subroutine return address ends

Threads • A thread may have dependant threads and subroutines which it uses to complete the logic of the entire program – Thread dependants must be listed by name somewhere within the body of a thread using either the “precedes” keyword or the “follows” keyword. – Use "thread <name>" to begin a thread and "endt" to end it. – If the "exit" opcode is missing the compiler handles scheduling dependants. thread main precedes waiter, worker /* thread body goes here */ // finalize this thread and schedule threads in the // specified range to execute exit // all dependants are automatically scheduled endt thread waiter /* thread body goes here */ // exit ; exit is optional due to smart compiler finalization endt thread worker precedes waiter /* thread body goes here */ exit // only one dependent – schedule it to execute endt

Subroutines • A subroutine is a type of thread that is designed to be called explicitly by other threads or subroutines. – You can pass arguments into and out of subroutines using global variables. – If a subroutine is designed to be used by concurrently executing threads then calls to the subroutine must be protected by acquiring a mutex. – Use "subroutine <name>" to begin a subroutine and "ends" to end it. – To return to the calling thread a subroutine uses the subret or return opcodes. thread main /* thread body goes here */ acquire ss. Mutex call Shared. Sub ; automatic return address (must be a "subroutine") release ss. Mutex subcall Another. Sub, anothersub_returnaddress ; manual return address // exit ; exit is optional due to smart compiler finalization endt subroutine Shared. Sub /* subroutine body goes here */ return ; return or subret is required as the last operation in a subroutine ends thread Another. Sub /* threads can be subroutines too */ subret anothersub_returnaddress ; manually handling the return address endt

Opcode Overview • Families – Memory, Math, Logic, Bit Manipulation, Comparison, Control Flow, Timing, Arrays, Strings, Scheduling, and IO • Argument Types – Valid argument types include variables, constants, IO Map addresses (IOMA), labels, and thread names – Output (dest) arguments must be a variable or an IOMA. Input (src) arguments can be a variable, an IOMA, or a constant expression • Variables can be scalar, array, or struct types • Use dot notation to reference struct members (x. y. z) • The compiler introduces a temporary variable for each constant expression used where a variable or IOMA is expected (only for input arguments) – IOMA are special constants which provide direct access to input and output field values

Memory • All opcodes in this family have one output argument and one input argument mov x, y // set x equal to y set x, 10 // set x equal to 10 – mov arguments must be compatible (struct to struct, array to array, scalar to scalar) • Scalar types do not have to match – set requires that its output argument be a scalar variable or an IOMA. Its input argument must be a constant or constant expression. • Input argument is limited to a 16 bit signed or unsigned value

Math • All opcodes in this family have one output argument and two input arguments except negate, absolute value, and sign – Can use scalar, array, and aggregate argument types add set incr, 1 add x, x, incr // increment x by 1 sub set decr, 1 sub x, x, decr // decrement x by 1 mul x, x, x // x = sqr(x) div x, x, 2 // x = x / 2 (integer division) // (a temporary will be introduced by the compiler in this case) mod x, x, 4 // x = x % 4 (remainder) // (set x to 0. . 3 – uses a temporary in this case)

Math (cont. ) neg x, x // x = -x (unary operator) abs x, y // x = abs(y) (absolute value) sign x, y // x = sign(y) (-1, 0, 1)

Logic • All opcodes in this family have one output argument and two input arguments except logical not – Can use scalar, array, and aggregate argument types and x, x, y // x = x & y (if x = b 1010 and y = b 0110 then x & y = 0010) or or x, x, y // x = x | y (if x = b 1010 and y = b 0110 then x | y = 1110) xor x, x, y // x = x ^ y (if x = b 1010 and y = b 0110 then x ^ y = 1100) not x, x // x = !x // the firmware implements not as a logical operation – not a bitwise operation

Bit Manipulation • All opcodes in this family have one output argument and two input arguments shr result, value, bits shr my. Val, 3 // divide my. Val by 2 three times shl result, value, bits shl my. Val, 2 ; multiply my. Val by 2 twice • These opcodes are implemented by the compiler since the standard NXT firmware does not support shift operations at this time.

Comparison • These opcodes all take a comparison code constant as their first argument – Can use scalar, array, and aggregate types for the compare or test argument(s) – Valid comparison codes • • • Less than: LT = 0 x 00 ('<' may also be used) Greater than: GT = 0 x 01 ('>' may also be used) Less than or equal to: LTEQ = 0 x 02 ('<=' may also be used) Greater than or equal to: GTEQ = 0 x 03 ('>=' may also be used) Equal to: EQ = 0 x 04 ('==' may also be used) Not equal to: NEQ = 0 x 05 ('!=' or '<>' may also be used) cmp cc, dest, src 1, src 2 cmp EQ, b. Equal, x, y // set b. Equal to true if x == y tst cc, dest, src tst GT, b. GTZero, x // set b. GTZero to true if x > 0 cmpset cc, dest, src, testsrc (not implemented in NXT FW) tstset cc, dest, src, testsrc (not implemented in NXT FW)

Control Flow • The jump opcode takes a label as its only argument and unconditionally jumps to that program location jmp label Loop. Start: // loop body jmp Loop. Start // jump to Loop. Start label • The branch opcodes take a comparison code constant as their first argument (see Comparison) and a label for the second argument brcmp cc, label, src 1, src 2 brcmp EQ, Equal. Values, x, y // jump to Equal. Values label if x == y brtst cc, label, src brtst GT, XGt. Zero, x // jump to XGt. Zero label if x > 0 • The stop opcode stops program execution depending on the value of its boolean input argument stop? stop b. Stop // stop the program if b. Stop is true (non-zero)

System Calls • The syscall opcode enables execution of various system functions via a constant function ID and an aggregate type variable for passing arguments to and from the system function syscall function. ID, args syscall Sound. Play. Tone, pt. Args // pt. Args is a struct with input and output args – Function identifiers: File. Open. Read (0), File. Open. Write (1), File. Open. Append (2), File. Read (3), File. Write (4), File. Close (5), File. Resolve. Handle (6), File. Rename (7), File. Delete (8), Sound. Play. File (9), Sound. Play. Tone (10), Sound. Get. State (11), Sound. Set. State (12), Draw. Text (13), Draw. Point (14), Draw. Line (15), Draw. Circle (16), Draw. Rect (17), Draw. Graphic (18), Set. Screen. Mode (19), Read. Button (20), Comm. LSWrite (21), Comm. LSRead (22), Comm. LSCheck. Status (23), Random. Number (24), Get. Start. Tick (25), Message. Write (26), Message. Read (27), Comm. BTCheck. Status (28), Comm. BTWrite (29), Keep. Alive (31), IOMap. Read (32), IOMap. Write (33)

Timing • The wait opcode suspends the current thread for the number of milliseconds specified by its constant argument wait 1000 // wait for 1 second • The waitv opcode acts like wait but it takes a variable argument waitv i. Delay // wait for the specified number of ms. • The gettick opcode sets its output argument to the current system tick count gettick x // set x to the current system tick count – NBC implements wait and waitv as thread-specific subroutine calls due to the wait opcode not having been implemented in the NXT firmware – If you use a constant argument with waitv the compiler will generate a temporary variable for you – If needed, you can implement simple wait loops using gettick: gettick curr. Tick add end. Tick, curr. Tick, waitms Loop: gettick curr. Tick brcmp LT, Loop, curr. Tick, end. Tick
![Arrays • The index opcode returns the arraysrc[index] value in the dest output argument Arrays • The index opcode returns the arraysrc[index] value in the dest output argument](http://slidetodoc.com/presentation_image_h2/d4a03fe2f17d7c589c1dcd9aff14d859/image-23.jpg)
Arrays • The index opcode returns the arraysrc[index] value in the dest output argument index dest, arraysrc, index val, ar. Values, idx // extract ar. Values[idx] and store it in val • The replace opcode replaces the arraysrc[index] item in arraydest with the newval input argument (arraysrc can be the same variable as arraydest to replace without copying the array; newval can be an array, in which case multiple items are replaced) replace arraydest, arraysrc, index, newval replace ar. New, ar. Values, idx, x // replace ar. Values[idx] with x in ar. New • The arrsize opcode returns the size of the input array in the scalar dest output argument arrsize dest, arraysrc arrsize n. Size, ar. Values // n. Size == length of array

Arrays (cont. ) • The arrinit opcode initializes the output array to the value and size provided arrinit arraydest, value, size arrinit ar. Values, n. Zero, n. Size // initialize ar. Values with n. Size zeros • The arrsubset opcode copies a subset of the input array to the output array arrsubset arraydest, arraysrc, index, length arrsubset ar. Sub, ar. Values, NA, x // copy the first x elements to ar. Sub • The arrbuild opcode constructs an output array from a variable number of input arrays, scalars, or aggregates arrbuild arraydest, src 1, src 2, …, src. N arrbuild ar. Data, ar. Start, ar. Body, ar. End // build data array from 3 sources

Strings (1) • The flatten opcode converts input argument into its string output argument flatten strdest, source flatten str. Data, args // copy from the args struct to str. Data • The unflatten opcode converts input string argument to the output argument type. If 'default' does not match the flattened data type exactly (including array sizes) then 'err' will be set to TRUE and 'dest' will contain a copy of 'default' unflatten dest, err, strsrc, default unflatten args, b. Err, str. Source, x // convert string to cluster • The numtostr opcode converts its scalar input argument to a string output argument numtostr deststr, source numtostr str. Value, value // convert value to a string • The strtonum opcode parses its input string argument into a numeric output argument, advancing an offset past the numeric string strtonum dest, offset. Next, str, offset. Cur, default strtonum value, idx, str. Value, idx, n. Zero // parse string into num

Strings (2) • The strsubset opcode copies a subset of the input string to the output string strsubset strdest, strsrc, index, length strsubset str. Sub, str. Source, NA, x // copy the first x bytes in str. Source to str. Sub • The strcat opcode constructs an output string from a variable number of input strings strcat strdest, strsrc 1, strsrc 2, …, strsrc. N strcat str. Data, str. Start, str. Body, str. End // build data string from 3 sources • The arrtostr opcode copies the input byte array into its output string array and adds a null byte at the end arrtostr strdest, arraysrc arrtostr str. Data, arr. Data // convert byte array to string • The strtoarr opcode copies the input string array into its output byte array excluding the last byte (which should be a null) strtoarr arraydest, strsrc strtoarr arr. Data, str. Data // convert string to byte array
![Strings (3) • The strindex opcode returns the strsrc[index] value in the dest output Strings (3) • The strindex opcode returns the strsrc[index] value in the dest output](http://slidetodoc.com/presentation_image_h2/d4a03fe2f17d7c589c1dcd9aff14d859/image-27.jpg)
Strings (3) • The strindex opcode returns the strsrc[index] value in the dest output argument strindex dest, strsrc, index strindex val, str. Val, idx // extract str. Val[idx] and store it in val • The strreplace opcode replaces the strsrc[index] item in strdest with the newval input argument (strsrc can be the same variable as strdest to replace without copying the string; newval can be a string, in which case multiple items are replaced) strreplace strdest, strsrc, index, newval strreplace str. New, str. Values, idx, new. Str // replace str. Values[idx] with new. Str in str. New • The strlen opcode returns the size of the input string in the scalar output argument strlen dest, strsrc strlen n. Size, str. Msg // n. Size == length of str. Msg

Scheduling • The exit opcode finalizes the current thread and schedules zero or more dependant threads by specifying start and end dependency list indices (indices are zero-based and inclusive) exit [start, end] exit 0, 2 // schedule this thread's 3 dependants exit // schedule all this thread's dependants • The exitto opcode finalizes the current thread and schedules the thread specified by name exitto worker // exit now and schedule worker thread • The acquire opcode acquires the named mutex. If the mutex is already acquired the current thread waits until it becomes available acquire mu. Foo // acquire mutex for subroutine • The release opcode releases the named mutex allowing other threads to acquire it release mu. Foo // release mutex for subroutine

Scheduling (cont. ) • The subcall opcode calls into the named thread/subroutine and waits for a return (which might not come from the same thread) – The second argument is a variable used to store the return address subcall draw. Text, ret. Draw. Text // call draw. Text subroutine • The subret opcode returns from a thread to the return address value contained in its input argument subret ret. Draw. Text // return to calling routine • The call opcode executes the named subroutine and waits for a return. The argument should specify a thread that was declared using the "subroutine" keyword. call My. Favorite. Subroutine // call routine • The return opcode returns from a subroutine. return // return to calling routine • The compiler automatically handles the return address for call and return when they are used with subroutines rather than threads

Inputs • The setin opcode sets an input field of a sensor on a port to the value specified in its first input argument setin src, port, field. ID set the. Type, IN_TYPE_SWITCH // set type to switch set the. Mode, IN_MODE_BOOLEAN // set mode to boolean set the. Port, IN_1 // set port to #1 setin the. Type, the. Port, Type // set sensor on port 1 to switch type setin the. Mode, the. Port, Input. Mode // set sensor on port 1 to boolean mode – Input Field Identifiers Type (0), Input. Mode (1), Raw. Value (2), Normalized. Value (3), Scaled. Value (4), Invalid. Data (5) • The getin opcode reads a value from an input field of a sensor on a port and writes the value to its dest output argument getin dest, port, field. ID getin r. Val, the. Port, Raw. Value // read raw sensor value getin s. Val, the. Port, Scaled. Value // read scaled sensor value getin n. Val, the. Port, Normalized. Value // read normalized sensor value

Outputs • The setout opcode sets one or more output fields of a motor on one or more ports to the value specified by the coupled input arguments setout port/portlist, fieldid 1, value 1, …, fieldid. N, value. N set the. Mode, OUT_MODE_MOTORON // set mode to motor on set rs. Val, OUT_RUNSTATE_RUNNING // motor running set the. Port, OUT_A // set port to #1 (use an array for multiple ports) set pwr, -75 // negative power means reverse motor direction // set output values setout the. Port, Output. Mode, the. Mode, Run. State, rs. Val, Power, pwr – Output Field Identifiers Update. Flags (0), Output. Mode (1), Power (2), Actual. Speed (3), Tacho. Count (4), Tacho. Limit (5), Run. State (6), Turn. Ratio (7), Reg. Mode (8), Overload (9), Reg. PValue (10), Reg. IValue (11), Reg. DValue (12), Block. Tacho. Count (13), Rotation. Count (14) • The getout opcode reads a value from an output field of a sensor on a port and writes the value to its dest output argument getout dest, port, field. ID getout rm. Val, the. Port, Reg. Mode // read motor regulation mode getout tl. Val, the. Port, Tacho. Limit // read tachometer limit value getout rc. Val, the. Port, Rotation. Count // read the rotation count

IO Map Addresses • IOMA constants provide a simplified means for accessing input and output field values – Instead of: set the. Type, IN_TYPE_SWITCH // set type to switch set the. Mode, IN_MODE_BOOLEAN // set mode to boolean set the. Port, IN_1 // set port to #1 (0) setin the. Type, the. Port, Type // set sensor on port 1 to switch type setin the. Mode, the. Port, Input. Mode // set sensor on port 1 to boolean mode getin r. Val, the. Port, Raw. Value // read raw sensor value getin s. Val, the. Port, Scaled. Value // read scaled sensor value getin n. Val, the. Port, Normalized. Value // read normalized sensor value getout rm. Val, the. Port, Reg. Mode // read output regulation mode – You can use: set mov mov set mov Input. IOType 0, IN_TYPE_SWITCH // set type to switch Input. IOInput. Mode 0, IN_MODE_BOOLEAN // set mode to boolean r. Val, Input. IORaw. Value 0 // read raw sensor value s. Val, Input. IOScaled. Value 0 // read scaled value n. Val, Input. IONormalized. Value 0 // read normalized value Output. IORun. State 0, OUT_RUNSTATE_RUNNING // set motor A run state Output. IOPower 0, -75 // set motor A power rm. Val, Output. IOReg. Mode 0 // read motor A regulation mode rc. Val, Output. IORotation. Count 0 // read motor A rotation count

Compile-time Operations • Compiler operations sizeof(arg) // returns the compile-time size of the specified argument dseg segment arg byte argsize byte dseg ends //. . . set argsize, sizeof(arg) ; argsize == 1 • Compiler opcodes compchk cc, const 1, const 2 compchk EQ, sizeof(arg 3), 2 – Reports a compiler error if the expression does not evaluate to true.

Expression Evaluator • Constant expressions are supported for many opcode arguments – Expressions are evaluated at compile time (not at run time) – Expressions must not contain whitespace (4+4, not 4 + 4) – Supported operators: • +, -, *, / , ^ (power), % (modulo), &, |, <<, and >> • () for grouping subexpressions • PI constant – Supported compile-time functions: • tan, sin, cos, sinh, cosh, arctan, cotan, arg, exp, ln, log 10, log 2, logn, sqrt, abs, trunc, int, ceil, floor, heav, sign, zero, ph, rnd, random, max, min, power, intpower – Example: set val, 3+(PI*2)-sqrt(30) // expression value will be truncated to an integer

Snippets: Inputs dseg segment the. Sensor. Type byte the. Sensor. Mode byte is. Invalid byte the. Port byte SVal sword RVal word NVal word dseg ends thread main set the. Port, IN_1 // set sensor type and mode set the. Sensor. Type, IN_TYPE_SWITCH set the. Sensor. Mode, IN_MODE_BOOLEAN setin the. Sensor. Type, the. Port, Type setin the. Sensor. Mode, the. Port, Input. Mode /* when changing the type and/or mode of a sensor the NXT blocks also set the Invalid. Data field to true */ set is. Invalid, TRUE setin is. Invalid, the. Port, Invalid. Data // make sure the sensor value is valid still. Invalid: getin is. Invalid, the. Port, Invalid. Data brtst NEQ, still. Invalid, is. Invalid /* if is. Invalid not false (equal to zero) then loop until it is */ /* set sensor values (the NXT blocks reset the Scaled. Value to zero before reading it shortly afterward) */ set SVal, 0 setin SVal, the. Port, Scaled. Value // read sensor values getin SVal, the. Port, Scaled. Value getin RVal, the. Port, Raw. Value getin NVal, the. Port, Normalized. Value exit endt

Snippets: Inputs IOMA dseg segment SVal sword RVal word NVal word dseg ends // make sure the sensor value is valid still. Invalid: brtst NEQ, still. Invalid, Input. IOInvalid. Data 0 /* if Invalidata is not false (equal to zero) then loop until it is */ thread main // set sensor type and mode set Input. IOType 0, IN_TYPE_SWITCH /* set sensor values (the NXT blocks reset the Scaled. Value to zero before reading it shortly afterward) */ // reading raw sensor values this time set Input. IOInput. Mode 0, IN_MODE_RAW set Input. IOScaled. Value 0, 0 // read sensor values /* when changing the type and/or mode of a sensor the NXT blocks also set the Invalid. Data field to true */ mov SVal, Input. IOScaled. Value 0 mov RVal, Input. IORaw. Value 0 mov NVal, Input. IONormalized. Value 0 set Input. IOInvalid. Data 0, TRUE exit endt

Snippets: Outputs dseg segment the. UF byte the. Power sbyte the. OM byte OUT_MODE_MOTORON+OUT_MODE_BRAKE the. RM byte OUT_REGMODE_IDLE the. RS byte OUT_RUNSTATE_RUNNING dseg ends thread main set the. UF, UF_UPDATE_MODE ; initialize motor setout OUT_A, Output. Mode, the. OM, Reg. Mode, the. RM, Run. State, the. RS, Update. Flags, the. UF Forever: set the. Power, 90 Update. Speed: set the. UF, UF_UPDATE_SPEED+UF_UPDATE_MODE setout OUT_A, Power, the. Power, Output. Mode, the. OM, Update. Flags, the. UF jmp Forever exit endt

Snippets: Outputs IOMA thread main set Output. IOOutput. Mode 0, OUT_MODE_MOTORON+OUT_MODE_BRAKE set Output. IOReg. Mode 0, OUT_REGMODE_IDLE set Output. IORun. State 0, OUT_RUNSTATE_RUNNING set Output. IOUpdate. Flags 0, UF_UPDATE_MODE ; initialize motor Forever: set Output. IOPower 0, 90 set Output. IOOutput. Mode 0, OUT_MODE_MOTORON+OUT_MODE_BRAKE set Output. IOUpdate. Flags 0, UF_UPDATE_SPEED+UF_UPDATE_MODE jmp Forever exit endt

Sys. Call: File. Open. Read ; define structure TFile. Open struct Result word File. Handle byte Filename byte[] 'test. txt' Length dword TFile. Open ends ; declare variables FOR_A TFile. Open fh byte ; call the API syscall File. Open. Read, FOR_A ; copy the filehandle for later use mov fh, FOR_A. File. Handle

Sys. Call: File. Open. Write ; define structure TFile. Open struct Result word File. Handle byte Filename byte[] 'test. txt' Length dword TFile. Open ends ; declare variables FOW_A TFile. Open fh byte ; call the API syscall File. Open. Write, FOW_A ; copy the filehandle for later use mov fh, FOW_A. File. Handle

Sys. Call: File. Open. Append ; define structure TFile. Open struct Result word File. Handle byte Filename byte[] 'test. txt' Length dword TFile. Open ends ; declare variables FOA_A TFile. Open fh byte ; call the API syscall File. Open. Append, FOA_A ; copy the filehandle for later use mov fh, FOA_A. File. Handle

Sys. Call: File. Read dseg segment ; define structure TFile. Read. Write Result word File. Handle byte Buffer byte[] Length dword TFile. Read. Write struct ends ; declare variables FR_A TFile. Read. Write fh byte tmp. Str byte[] bytes. Read dword dseg ends thread main //. . . mov FR_A. File. Handle, fh ; file handle obtained via File. Open. Read set FR_A. Length, 10 ; specify buffer size and desired number of bytes to read syscall File. Read, FR_A ; call the API mov tmp. Str, FR_A. Buffer ; copy the Buffer for later use mov bytes. Read, FR_A. Length ; store the actual # of bytes read endt

Sys. Call: File. Write dseg segment ; define structure TFile. Read. Write Result word File. Handle byte Buffer byte[] Length dword TFile. Read. Write struct ends ; declare variables FW_A TFile. Read. Write fh byte tmp. Str byte[] 'testing' bytes. Written dword dseg ends thread main //. . . mov FW_A. File. Handle, fh ; file handle obtained via File. Open. Write mov FW_A. Buffer, tmp. Str ; copy data into write Buffer syscall File. Write, FW_A ; call the API mov bytes. Written, FW_A. Length ; store the number of bytes written endt

Sys. Call: File. Close dseg segment ; define structure TFile. Close struct Result word File. Handle byte TFile. Close ends ; declare variables FC_A TFile. Close fh byte dseg ends thread main //. . . mov FC_A. File. Handle, fh ; file handle obtained via File. Open* syscall File. Close, FC_A ; call the API endt

Sys. Call: File. Resolve. Handle dseg segment ; define structure TFile. Resolve. Handle Result word File. Handle byte Write. Handle byte Filename byte[] TFile. Resolve. Handle struct ends ; declare variables FRH_A TFile. Resolve. Handle fh byte b. Writeable byte the. Filename byte[] 'myfile. txt' dseg ends thread main //. . . mov FRH. Filename, the. Filename ; pass in a filename syscall File. Resolve. Handle, FRH_A ; call the API mov fh, FRH_A. File. Handle ; store the resolved handle mov b. Writeable, FRH_A. Write. Handle ; is this a writeable handle? endt

Sys. Call: File. Rename dseg segment ; define structure TFile. Rename struct Result word Old. Filename byte[] New. Filename byte[] TFile. Rename ends ; declare variables FR_A TFile. Close fh byte dseg ends thread main //. . . mov FR_A. Old. Filename, 'oldfile. txt' ; old filename mov FR_A. New. Filename, 'newfile. txt' ; new filename syscall File. Rename, FR_A ; call the API endt

Sys. Call: File. Delete dseg segment ; define structure TFile. Delete struct Result word Filename byte[] TFile. Delete ends ; declare variables FD_A TFile. Close fh byte the. Filename byte[] 'delete_me. txt' dseg ends thread main //. . . mov FD_A. Filename, the. Filename ; filename to be deleted syscall File. Delete, FD_A ; call the API endt

Sys. Call: Sound. Play. File • Define the record • Call the API dseg segment ; definition Sound. PF_def struct result sbyte filename byte[] loop byte vol byte Sound. PF_def ends ; declarations PT_A Sound. PT_def sound. File byte[] 'mysound. rso' dseg ends ; code set PF_A. loop, 0 ; no looping set PF_A. vol, 3 ; percent/25 mov PF_A. filename, sound. File syscall Sound. Play. File, PF_A • Wait for completion – NXT has no sound queue dseg segment ; definition Sound. GS_def struct result byte flags byte Sound. GS_def ends ; declaration SGS Sound. GS_def dseg ends ; code stillplaying: syscall Sound. Get. State, SGS brtst NEQ, stillplaying, SGS. flags

Sys. Call: Sound. Play. Tone • Define the record • Call the API ; definition Sound. PT_def struct result sbyte freq word time word loop byte vol byte Sound. PT_def ends ; declarations PT_A Sound. PT_def ; code set PT_A. freq, 440 ; A set PT_A. time, 1000 ; 1 sec set PT_A. loop, 0 ; no looping set PT_A. vol, 3 ; percent/25 syscall Sound. Play. Tone, PT_A • Wait for completion – NXT has no sound queue ; definition Sound. GS_def struct result byte flags byte Sound. GS_def ends ; declaration SGS Sound. GS_def ; code stillplaying: syscall Sound. Get. State, SGS brtst NEQ, stillplaying, SGS. flags

Sys. Call: Sound. Get. State • Define the record • Call the API ; definition Sound. GS_def struct state byte flags byte Sound. GS_def ends ; declaration SGS Sound. GS_def ; code stillplaying: syscall Sound. Get. State, SGS brtst NEQ, stillplaying, SGS. flags

Sys. Call: Sound. Set. State • Define the record • Call the API dseg segment ; definition TSound. Set. State Result State Flags TSound. Set. State struct byte ends ; declaration SSS_A TSound. Set. State dseg ends ; code set SSS. State, 0 x 04 ; stop playing set SSS. Flags, 0 x 01 ; make changes take effect syscall Sound. Set. State, SSS ; call the API

Sys. Call: Draw. Text dseg segment TLocation X Y TLocation struct sword ends TDraw. Text Result Location Text Options TDraw. Text struct sbyte TLocation byte[] dword ends ; declaration dt. Args TDraw. Text value dword dseg ends ; code set dt. Args. Location. X, 10 set dt. Args. Location. Y, 8 set dt. Args. Options, 1 ; erase previous text set value, 13 numtostr dt. Args. Text, value ; set the text to draw syscall Draw. Text, dt. Args ; call the API

Sys. Call: Draw. Point dseg segment TLocation X Y TLocation struct sword ends TDraw. Point Result Location Options TDraw. Point struct sbyte TLocation dword ends ; declaration dp. Args TDraw. Point dseg ends ; code set dp. Args. Location. X, 10 set dp. Args. Location. Y, 8 set dp. Args. Options, 1 ; erase screen before drawing syscall Draw. Point, dp. Args ; call the API

Sys. Call: Draw. Line dseg segment TLocation X Y TLocation struct sword ends TDraw. Line Result Start. Loc End. Loc Options TDraw. Line struct sbyte TLocation dword ends ; declaration dl. Args TDraw. Line dseg ends ; code set dl. Args. Start. Loc. X, 10 set dl. Args. Start. Loc. Y, 8 set dl. Args. End. Loc. X, 50 set dl. Args. End. Loc. Y, 30 set dl. Args. Options, 1 ; erase screen before drawing syscall Draw. Line, dl. Args ; call the API

Sys. Call: Draw. Circle dseg segment ; definition TLocation X Y TLocation struct sword ends TDraw. Circle Result Center Size Options TDraw. Circle struct sbyte TLocation byte dword ends ; declaration dc. Args TDraw. Circle dseg ends ; code set dc. Args. Center. X, 30 set dc. Args. Center. Y, 20 set dc. Args. Size, 10 set dc. Args. Options, 0 ; don't clear the screen syscall Draw. Circle, dc. Args ; call the API

Sys. Call: Draw. Rect dseg segment TLocation X Y TLocation struct sword ends TSize Width Height TSize struct sword ends TDraw. Rect Result Location Size Options TDraw. Rect struct sbyte TLocation TSize dword ends dr. Args TDraw. Rect dseg ends ; code set dr. Args. Location. X, 30 set dr. Args. Location. Y, 20 set dr. Args. Size. Width, 20 set dr. Args. Size. Height, 10 set dr. Args. Options, 0 ; don't clear the screen syscall Draw. Rect, dr. Args ; call the API

Sys. Call: Draw. Graphic dseg segment ; definition TLocation X Y TLocation struct sword ends TDraw. Graphic Result Location Filename Variables Options TDraw. Graphic struct sbyte TLocation byte[] sdword[] dword ends ; declaration dg. Args TDraw. Graphic dseg ends ; code set dg. Args. Location. X, 30 set dg. Args. Location. Y, 20 mov dg. Args. Filename, 'picture. ric' ; let compiler create temporary string set dg. Args. Options, 0 ; do not clear screen syscall Draw. Graphic, dg. Args ; call the API

Sys. Call: Set. Screen. Mode • Define the record • Call the API TSet. Screen. Mode struct Result byte Screen. Mode dword TSet. Screen. Mode ends ; declaration SSM_A TSet. Screen. Mode dseg ends ; code set SSM_A. Screen. Mode, 0 ; erase the screen syscall Set. Screen. Mode, SSM_A ; call the API /* calling Set. Screen. Mode with any Screen. Mode value other than zero has no effect. 0 == RESTORE_NXT_SCREEN */

Sys. Call: Read. Button ; declarations TRead. Button Result Index Pressed Count Reset TRead. Button struct sbyte byte ends rb. Args TRead. Button b. Pressed 2 byte ; code set rb. Args. Index, BTN 3 syscall Read. Button, rb. Args ; call the API mov b. Pressed 2, rb. Args. Pressed set rb. Args. Index, BTN 3 set rb. Args. Reset, TRUE syscall Read. Button, rb. Args ; reset the button

Sys. Call: Comm. LSWrite ; declarations TComm. LSWrite Result Port Buffer Return. Len TComm. LSWrite struct sbyte[] byte ends lsw. Args TComm. LSWrite buf. LSWrite 1 byte[] 0 x 2, 0 x 42 ; code // first configure sensor port as IN_TYPE_LOWSPEED_9 V and IN_MODE_RAW // (not shown) mov lsw. Args. Port, the. Port set lsw. Args. Return. Len, 1 mov lsw. Args. Buffer, buf. LSWrite 1 syscall Comm. LSWrite, lsw. Args // now you can check status and read. . .

Sys. Call: Comm. LSRead ; declarations TComm. LSRead Result Port Buffer. Len TComm. LSRead struct sbyte[] byte ends lsr. Args TComm. LSRead read. Buf byte[] ls. Bytes. Read byte RLSBRet. Val byte ; code // first configure sensor port as IN_TYPE_LOWSPEED_9 V and IN_MODE_RAW // (not shown) // then write to the LS sensor port using Comm. LSWrite mov lsr. Args. Port, the. Port set lsr. Args. Buffer. Len, 1 syscall Comm. LSRead, lsr. Args mov read. Buf, lsr. Args. Buffer arrsize ls. Bytes. Read, read. Buf index RLSBRet. Val, read. Buf, NA

Sys. Call: Comm. LSCheck. Status ; declarations TComm. LSCheck. Status Result Port Bytes. Ready TComm. LSCheck. Status struct sbyte ends lscs. Args TComm. LSCheck. Status ; code thread Check. LSStat mov lscs. Args. Port, the. Port syscall Comm. LSCheck. Status, lscs. Args tst LT, b. LSStat. LT 0, lscs. Args. Result tst EQ, b. LSStat. EQ 0, lscs. Args. Result subret chkls_ret endt

Sys. Call: Random. Number ; declarations TRandom. Number struct Result sword TRandom. Number ends rn. Args TRandom. Number value sword ; code syscall Random. Number, rn. Args mov value, rn. Args. Result

Sys. Call: Get. Start. Tick ; declarations TGet. Start. Tick struct Result dword TGet. Start. Tick ends gst. Args TGet. Start. Tick cur. Tick dword ; code syscall mov Get. Start. Tick, gst. Args cur. Tick, gst. Args. Result

Sys. Call: Message. Write ; declarations TMessage. Write Result Queue. ID Message TMessage. Write struct sbyte[] ends mw. Args TMessage. Write ; code syscall Message. Write, mw. Args

Sys. Call: Message. Read ; declarations TMessage. Read Result Queue. ID Remove Message TMessage. Read struct sbyte byte[] ends mr. Args TMessage. Read ; code syscall Message. Read, mr. Args

Sys. Call: Comm. BTCheck. Status ; declarations TComm. BTCheck. Status Result Connection byte TComm. BTCheck. Status struct sbyte ends bcs. Args TComm. BTCheck. Status ; code syscall Comm. BTCheck. Status, bcs. Args

Sys. Call: Comm. BTWrite ; declarations TComm. BTWrite Result Connection Buffer TComm. BTWrite struct sbyte[] ends btw. Args TComm. BTWrite ; code syscall Comm. BTWrite, btw. Args

Sys. Call: Keep. Alive ; declarations TKeep. Alive struct Result dword TKeep. Alive ends ka. Args TKeep. Alive val dword ; code syscall mov Keep. Alive, ka. Args val, ka. Args. Result // current sleep time

Sys. Call: IOMap. Read TIOMap. Read Result sbyte Module. Name Offset word Count word Buffer byte[] TIOMap. Read struct byte[] ends iomr. Args TIOMap. Read blevel sdword b 1 byte b 2 byte mov iomr. Args. Module. Name, 'Ui. mod' set iomr. Args. Offset, 4 // UIOffset. Battery. Level set iomr. Args. Count, 2 // Battery level is 2 bytes syscall IOMap. Read, iomr. Args // two bytes go into blevel index b 1, iomr. Args. Buffer, NA // 0 index b 2, iomr. Args. Buffer, 1 mul blevel, b 2, 256 add blevel, b 1

Sys. Call: IOMap. Write // Put the NXT dseg segment TIOMap. Write Result Module. Name Offset Buffer TIOMap. Write into boot mode struct sbyte[] word byte[] ends iomw. Args TIOMap. Write data. Buf byte[] 0 x 5 A, 0 x. A 5 // boot dseg ends ; ------- program code -------thread main mov iomw. Args. Module. Name, 'IOCtrl. mod' set iomw. Args. Offset, 0 ; IOCtrl. Offset. Power. On mov iomw. Args. Buffer, data. Buf syscall IOMap. Write, iomw. Args exit endt

Predefined Constants (1) • See NBCCommon. h for a complete list of predefined constants – NA (0 x. FFFF) • Indicates a non-available argument • Can be used in certain operations to allow for a default behavior – stop – if the stop? argument is NA use true – index – if the index argument is NA use 0 – replace – if the index argument is NA use 0 – arrinit – if the size argument is NA use 0 – arrsubset – if the index argument is NA use 0, if the length argument is NA use the length of the source array – strsubset – if the index argument is NA use 0, if the length argument is NA use the length of the source string – strtonum – if the offset argument is NA use 0, if the default argument is NA use 0 – Boolean Values • TRUE (1), FALSE (0) – Output Ports • OUT_A (0 x 00), OUT_B (0 x 01), OUT_C (0 x 02) – Input Ports • IN_1 (0 x 00), IN_2 (0 x 01), IN_3 (0 x 02), IN_4 (0 x 03) – Comparison Codes • LT (0 x 00), GT (0 x 01), LTEQ (0 x 02), GTEQ (0 x 03), EQ (0 x 04), NEQ (0 x 05)

Predefined Constants (2) • See NBCCommon. h for a complete list of predefined constants – Update Flags • UF_UPDATE_MODE (0 x 01), UF_UPDATE_SPEED (0 x 02), UF_UPDATE_TACHO_LIMIT (0 x 04), UF_UPDATE_RESET_COUNT (0 x 08), UF_UPDATE_PID_VALUES (0 x 10), UF_UPDATE_RESET_BLOCK_COUNT (0 x 20), UF_UPDATE_RESET_ROTATION_COUNT (0 x 40), UF_PENDING_UPDATES (0 x 80) – Output Mode • OUT_MODE_COAST (0 x 00), OUT_MODE_MOTORON (0 x 01), OUT_MODE_BRAKE (0 x 02), OUT_MODE_REGULATED (0 x 04), OUT_MODE_REGMETHOD (0 x. F 0) – Output Run State • OUT_RUNSTATE_IDLE (0 x 00), OUT_RUNSTATE_RAMPUP (0 x 10), OUT_RUNSTATE_RUNNING (0 x 20), OUT_RUNSTATE_RAMPDOWN (0 x 40) – Output Regulation Mode • OUT_REGMODE_IDLE (0), OUT_REGMODE_SPEED (1), OUT_REGMODE_SYNC (2) – Input Types • IN_TYPE_NO_SENSOR (0 x 0), IN_TYPE_SWITCH (0 x 1), IN_TYPE_TEMPERATURE (0 x 2), IN_TYPE_REFLECTION (0 x 3), IN_TYPE_ANGLE (0 x 4), IN_TYPE_LIGHT_ACTIVE (0 x 5), IN_TYPE_LIGHT_INACTIVE (0 x 6), IN_TYPE_SOUND_DB (0 x 7), IN_TYPE_SOUND_DBA (0 x 8), IN_TYPE_CUSTOM (0 x 9), IN_TYPE_LOWSPEED (0 x. A), IN_TYPE_LOWSPEED_9 V (0 x. B), IN_TYPE_HISPEED (0 x. C) – Input Modes • IN_MODE_RAW (0 x 00), IN_MODE_BOOLEAN (0 x 20), IN_MODE_TRANSITIONCNT (0 x 40), IN_MODE_PERIODCOUNTER (0 x 60), IN_MODE_PCTFULLSCALE (0 x 80), IN_MODE_CELSIUS (0 x. A 0), IN_MODE_FAHRENHEIT (0 x. C 0), IN_MODE_ANGLESTEP (0 x. E 0), IN_MODE_SLOPEMASK (0 x 1 F), IN_MODEMASK (0 x. E 0)

Predefined Constants (3) • See NBCCommon. h for a complete list of predefined constants – IO Map Address Constants • IO_BASE (0 xc 000), MOD_INPUT (0 x 0000), MOD_OUTPUT (0 x 0200), IO_IN_FPP (6), IO_OUT_FPP (15) – IO Map Addresses for Inputs • Input. IOType 0 (0 xc 000), Input. IOInput. Mode 0 (0 xc 001), Input. IORaw. Value 0 (0 xc 002), Input. IONormalized. Value 0 (0 xc 003), Input. IOScaled. Value 0 (0 xc 004), Input. IOInvalid. Data 0 (0 xc 005), Input. IOType 1 (0 xc 006), Input. IOInput. Mode 1 (0 xc 007), Input. IORaw. Value 1 (0 xc 008), Input. IONormalized. Value 1 (0 xc 009), Input. IOScaled. Value 1 (0 xc 00 a), Input. IOInvalid. Data 1 (0 xc 00 b), Input. IOType 2 (0 xc 00 c), Input. IOInput. Mode 2 (0 xc 00 d), Input. IORaw. Value 2 (0 xc 00 e), Input. IONormalized. Value 2 (0 xc 00 f), Input. IOScaled. Value 2 (0 xc 010), Input. IOInvalid. Data 2 (0 xc 011), Input. IOType 3 (0 xc 012), Input. IOInput. Mode 3 (0 xc 013), Input. IORaw. Value 3 (0 xc 014), Input. IONormalized. Value 3 (0 xc 015), Input. IOScaled. Value 3 (0 xc 016), Input. IOInvalid. Data 3 (0 xc 017) – IO Map Addresses for Outputs • Output. IOUpdate. Flags 0 (0 xc 200), Output. IOOutput. Mode 0 (0 xc 201), Output. IOPower 0 (0 xc 202), Output. IOActual. Speed 0 (0 xc 203), Output. IOTacho. Count 0 (0 xc 204), Output. IOTacho. Limit 0 (0 xc 205), Output. IORun. State 0 (0 xc 206), Output. IOTurn. Ratio 0 (0 xc 207), Output. IOReg. Mode 0 (0 xc 208), Output. IOOverload 0 (0 xc 209), Output. IOReg. PValue 0 (0 xc 20 a), Output. IOReg. IValue 0 (0 xc 20 b), Output. IOReg. DValue 0 (0 xc 20 c), Output. IOBlock. Tacho. Count 0 (0 xc 20 d), Output. IORotation. Count 0 (0 xc 20 e), Output. IOUpdate. Flags 1 (0 xc 20 f), Output. IOOutput. Mode 1 (0 xc 210), Output. IOPower 1 (0 xc 211), Output. IOActual. Speed 1 (0 xc 212), Output. IOTacho. Count 1 (0 xc 213), Output. IOTacho. Limit 1 (0 xc 214), Output. IORun. State 1 (0 xc 215), Output. IOTurn. Ratio 1 (0 xc 216), Output. IOReg. Mode 1 (0 xc 217), Output. IOOverload 1 (0 xc 218), Output. IOReg. PValue 1 (0 xc 219), Output. IOReg. IValue 1 (0 xc 21 a), Output. IOReg. DValue 1 (0 xc 21 b), Output. IOBlock. Tacho. Count 1 (0 xc 21 c), Output. IORotation. Count 1 (0 xc 21 d), Output. IOUpdate. Flags 2 (0 xc 21 e), Output. IOOutput. Mode 2 (0 xc 21 f), Output. IOPower 2 (0 xc 220), Output. IOActual. Speed 2 (0 xc 221), Output. IOTacho. Count 2 (0 xc 222), Output. IOTacho. Limit 2 (0 xc 223), Output. IORun. State 2 (0 xc 224), Output. IOTurn. Ratio 2 (0 xc 225), Output. IOReg. Mode 2 (0 xc 226), Output. IOOverload 2 (0 xc 227), Output. IOReg. PValue 2 (0 xc 228), Output. IOReg. IValue 2 (0 xc 229), Output. IOReg. DValue 2 (0 xc 22 a), Output. IOBlock. Tacho. Count 2 (0 xc 22 b), Output. IORotation. Count 2 (0 xc 22 c)

Motor API Macros • • • On. Fwd(ports, power): start the motors turning at the specified power level On. Rev(ports, power): same as On. Fwd but in the opposite direction On. Fwd. Reg(ports, power, regmode): Same as On. Fwd but allows for choosing the regulation mode On. Rev. Reg(ports, power, regmode): Opposite direction of On. Fwd. Reg On. Fwd. Sync(ports, power, turnpct): Same as On. Fwd but allows synchronizing multiple motors On. Rev. Sync(ports, power, turnpct): Opposite direction of On. Fwd. Sync Rotate. Motor(ports, power, angle): Rotate motors at power for specified angle. Negative power settings turn the opposite direction. Rotate. Motor. Ex(ports, power, angle, turnpct, bsync): Same as Rotate. Motor but with additional ability to synchronize motors and specify a turn ratio Coast(ports): Stop motors without braking Off(ports): Stop motors with braking

Sensor API Macros • Port must be a numeric constant – – – – • Set. Sensor. Type(port, type): set sensor type. Set. Sensor. Mode(port, mode): set sensor mode. Clear. Sensor(port): clear the sensor (set to zero). Set. Sensor. Touch(port): set type and mode as touch sensor. Set. Sensor. Light(port): set type and mode as light sensor. Set. Sensor. Sound(port): set type and mode as sound sensor. Set. Sensor. Ultrasonic(port): set type and mode as ultrasonic sensor. Port can be either a variable or a constant – Reset. Sensor(port): wait for sensor value to become valid. – Read. Sensor(port, value): read sensor into value. – Read. Sensor. US(port, value): read ultrasonic sensor into value.

Drawing API Macros • • Text. Out(x, y, cls, text): draw the text at (x, y) and optionally clear the screen first Num. Out(x, y, cls, numeric): draw the number at (x, y) with optional clear Point. Out(x, y, cls): draw a point at (x, y) with optional clear Line. Out(x 1, y 1, x 2, y 2, cls): draw a line from (x 1, y 1) to (x 2, y 2) with optional clear Rect. Out(x, y, width, height, cls): draw a rectangle at (x, y) with specified width and height. Optionally clear before drawing Circle. Out(x, y, radius, cls): draw a circle centered at (x, y) with specified radius Graphic. Out(x, y, filename, variables, cls): draw the RIC icon file specified by filename at (x, y). Optionally clear before drawing. Use the included 16 element array of values as a transformation function for the commands in the RIC file.

Sound API Macros • • • Play. Tone(frequency, duration): play a tone. frequency is in Hz. duration is in milliseconds. Play. Tone. Ex(frequency, duration, volume, loop): play a tone at the specified volume. loop is a boolean value indicating whether to repeat the tone. Play. File(filename): play a sound (. rso) or melody (. rmd) file. Play. File. Ex(filename, volume, loop): play a sound or melody file at the specified volume. loop is a boolean value indicating whether to repeat the file. Get. Sound. State(state, flags): get the current state of the sound module. Set. Sound. State(state, flags, result): set the current state of the sound module.

Miscellaneous API Macros • • Send. Message(queue, msg, result): send a message to the specified queue. Receive. Message(queue, clear, msg, result): receive a message from the specified queue. Optionally clear the message from the queue. • Read. Button. Ex(idx, reset, pressed, count, result): read the specified button state and return pressed, count, and result. Optionally reset the button state. • Random(variable, maximum): read a random number into variable. The value will be between 0 and maximum. Signed. Random(variable): read a signed random number into variable. The value will be a signed 16 -bit value. • • • Reset. Sleep. Timer: reset the sleep timer to its initial value. Use this to keep the brick from powering down when the sleep timer has elapsed. Get. First. Tick(value): read the tick from program startup (4 bytes).

File API Macros • • Create. File(fname , fsize, handle, result): creates a new file with the specified name and size. Returns the write handle and a result code. Open. File. Append(fname , fsize, handle, result): opens the specified file for appending if it already exists. Returns the size, a write handle, and a result code. Open. File. Read(fname , fsize, handle, result): opens the specified file for reading if it already exists. Returns the size, a read handle, and a result code. Close. File(handle, result): closes the specified file handle and returns a result code. Resolve. Handle(fname, handle, writeable, result): returns a handle for the specified file if the file is already open for reading or writing/appending. writeable is set to TRUE if the handle is a write handle. It also returns a result code. Rename. File(oldname, newname, result): renames the specified file handle and returns a result code. Delete. File(fname, result): deletes the specified file handle and returns a result code.

IOMap Writing API Macros • • • Set. IOMap. Bytes(mod. Name, offset, cnt, arr. In): write cnt bytes to the specified module at the specified offset. Set. IOMap. Value(mod. Name, offset, n): write the value 'n' to the specified module at the specified offset. The following are module-specific versions of the generic Set. IOMap. Value macro – Set. UIModule. Value(offset, n) – Set. IOCtrl. Module. Value(offset, n) – Set. Loader. Module. Value(offset, n) – Set. Command. Module. Value(offset, n) – Set. Sound. Module. Value(offset, n) – Set. Button. Module. Value(offset, n) – Set. Input. Module. Value(offset, n) – Set. Output. Module. Value(offset, n) – Set. Low. Speed. Module. Value(offset, n) – Set. Display. Module. Value(offset, n) – Set. Comm. Module. Value(offset, n)

IOMap Reading API Macros • • • Get. IOMap. Bytes(mod. Name, offset, cnt, arr. Out): read cnt bytes from the specified module at the specified offset. Get. IOMap. Value(mod. Name, offset, n): read the value 'n' from the specified module at the specified offset. The following are module-specific versions of the generic Get. IOMap. Value macro – Get. UIModule. Value(offset, n) – Get. IOCtrl. Module. Value(offset, n) – Get. Loader. Module. Value(offset, n) – Get. Command. Module. Value(offset, n) – Get. Sound. Module. Value(offset, n) – Get. Button. Module. Value(offset, n) – Get. Input. Module. Value(offset, n) – Get. Output. Module. Value(offset, n) – Get. Low. Speed. Module. Value(offset, n) – Get. Display. Module. Value(offset, n) – Get. Comm. Module. Value(offset, n)

UI Module API Macros • • • • Get. Battery. Level(value) Get. Command. Flags(value) Get. UIState(value) Get. UIButton(value) Get. VMRun. State(value) Get. Battery. State(value) Get. Bluetooth. State(value) Get. Usb. State(value) Get. Sleep. Timeout(value) Get. Sleep. Timer(value) Get. Rechargeable. Battery(value) Get. Volume(value) Get. On. Brick. Program. Pointer(value) • • • Set. Command. Flags(n) Set. UIState(n) Set. UIButton(n) Set. VMRun. State(n) Set. Battery. State(n) Set. Bluetooth. State(n) Set. Usb. State(n) Set. Sleep. Timeout(n) Set. Sleep. Timer(n) • • • Set. Volume(value) Set. On. Brick. Program. Pointer(value) Force. Off(n)

IOCtrl Module API Macros • • Power. Down: immediately power down the NXT brick. Reboot. In. Firmware. Mode: immediately boot the NXT into firmware download mode. Loader Module API Macros • Get. Free. Memory(variable): read the amount of free flash memory into the provided variable (4 bytes).

Sound Module API Macros • • Get. Sound. Frequency(value) Get. Sound. Duration(value) Get. Sound. Sample. Rate(value) Get. Sound. Flags(value) Get. Sound. State(value) Get. Sound. Mode(value) Get. Sound. Volume(value) • • Set. Sound. Frequency(n) Set. Sound. Duration(n) Set. Sound. Sample. Rate(n) Set. Sound. Flags(n) Set. Sound. State(n) Set. Sound. Mode(n) Set. Sound. Volume(n)

Button Module API Macros • • • Get. Button. Press. Count(b, value) Get. Button. Long. Press. Count(b, value) Get. Button. Short. Release. Count(b, value) Get. Button. Long. Release. Count(b, value) Get. Button. State(b, value) • • • Set. Button. Press. Count(b, n) Set. Button. Long. Press. Count(b, n) Set. Button. Short. Release. Count(b, n) Set. Button. Long. Release. Count(b, n) Set. Button. State(b, n)

Input Module API Macros • • Get. In. Custom. Zero. Offset(p, n) Get. In. Sensor. Boolean(p, n) Get. In. Digi. Pins. Direction(p, n) Get. In. Digi. Pins. Status(p, n) Get. In. Digi. Pins. Output. Level(p, n) Get. In. Custom. Percent. Full. Scale(p, n) Get. In. Custom. Active. Status(p, n) • • Set. In. Custom. Zero. Offset(p, n) Set. In. Sensor. Boolean(p, n) Set. In. Digi. Pins. Direction(p, n) Set. In. Digi. Pins. Status(p, n) Set. In. Digi. Pins. Output. Level(p, n) Set. In. Custom. Percent. Full. Scale(p, n) Set. In. Custom. Active. Status(p, n)

Output Module API Macros • Get. Out. Pwn. Freq(v) • Set. Out. Pwn. Freq(v)

Low. Speed Module API Macros • • • • Get. LSInput. Buffer(p, offset, cnt, data) Get. LSInput. Buffer. In. Ptr(p, n) Get. LSInput. Buffer. Out. Ptr(p, n) Get. LSInput. Buffer. Bytes. To. Rx(p, n) Get. LSOutput. Buffer(p, offset, cnt, data) Get. LSOutput. Buffer. In. Ptr(p, n) Get. LSOutput. Buffer. Out. Ptr(p, n) Get. LSOutput. Buffer. Bytes. To. Rx(p, n) Get. LSMode(p, v) Get. LSChannel. State(p, v) Get. LSError. Type(p, v) Get. LSState(v) Get. LSSpeed(v) • • • • Set. LSInput. Buffer(p, offset, cnt, data) Set. LSInput. Buffer. In. Ptr(p, n) Set. LSInput. Buffer. Out. Ptr(p, n) Set. LSInput. Buffer. Bytes. To. Rx(p, n) Set. LSOutput. Buffer(p, offset, cnt, data) Set. LSOutput. Buffer. In. Ptr(p, n) Set. LSOutput. Buffer. Out. Ptr(p, n) Set. LSOutput. Buffer. Bytes. To. Rx(p, n) Set. LSMode(p, v) Set. LSChannel. State(p, v) Set. LSError. Type(p, v) Set. LSState(v) Set. LSSpeed(v)

Display Module API Macros • • Get. Display. Erase. Mask(n) Get. Display. Update. Mask(n) Get. Display(n) Get. Display. Flags(n) Get. Display. Text. Lines. Center. Flags(n) Get. Display. Normal(x, line, cnt, data) Get. Display. Popup(x, line, cnt, data) • • Set. Display. Erase. Mask(n) Set. Display. Update. Mask(n) Set. Display(n) Set. Display. Flags(n) Set. Display. Text. Lines. Center. Flags(n) Set. Display. Normal(x, line, cnt, data) Set. Display. Popup(x, line, cnt, data)

BT Comm Module API Macros • • • • • • • Get. BTDevice. Name(p, str) Get. BTDevice. Class(p, v) Get. BTDevice. Address(p, addr) Get. BTDevice. Status(p, v) Get. BTConnection. Name(p, str) Get. BTConnection. Class(p, v) Get. BTConnection. Pin. Code(p, str) Get. BTConnection. Address(p, addr) Get. BTConnection. Handle. Num(p, v) Get. BTConnection. Stream. Status(p, v) Get. BTConnection. Link. Quality(p, v) Get. Brick. Data. Name(str) Get. Brick. Data. Bluecore. Version(v) Get. Brick. Data. Address(addr) Get. Brick. Data. Bt. State. Status(v) Get. Brick. Data. Bt. Hardware. Status(v) Get. Brick. Data. Timeout. Value(v) Get. BTInput. Buffer(data) Get. BTInput. Buffer. In. Ptr(n) Get. BTInput. Buffer. Out. Ptr(n) Get. BTOutput. Buffer(data) Get. BTOutput. Buffer. In. Ptr(n) Get. BTOutput. Buffer. Out. Ptr(n) Get. BTDevice. Count(n) Get. BTDevice. Name. Count(n) • • • • • • • Set. BTDevice. Name(p, str) Set. BTDevice. Class(p, v) Set. BTDevice. Address(p, addr) Set. BTDevice. Status(p, v) Set. BTConnection. Name(p, str) Set. BTConnection. Class(p, v) Set. BTConnection. Pin. Code(p, str) Set. BTConnection. Address(p, addr) Set. BTConnection. Handle. Num(p, v) Set. BTConnection. Stream. Status(p, v) Set. BTConnection. Link. Quality(p, v) Set. Brick. Data. Name(str) Set. Brick. Data. Bluecore. Version(v) Set. Brick. Data. Address(addr) Set. Brick. Data. Bt. State. Status(v) Set. Brick. Data. Bt. Hardware. Status(v) Set. Brick. Data. Timeout. Value(v) Set. BTInput. Buffer(data) Set. BTInput. Buffer. In. Ptr(n) Set. BTInput. Buffer. Out. Ptr(n) Set. BTOutput. Buffer(data) Set. BTOutput. Buffer. In. Ptr(n) Set. BTOutput. Buffer. Out. Ptr(n) Set. BTDevice. Count(n) Set. BTDevice. Name. Count(n)

USB/HS Comm Module API Macros • • • Get. USBInput. Buffer(data) Get. USBInput. Buffer. In. Ptr(n) Get. USBInput. Buffer. Out. Ptr(n) Get. USBOutput. Buffer(data) Get. USBOutput. Buffer. In. Ptr(n) Get. USBOutput. Buffer. Out. Ptr(n) Get. USBPoll. Buffer(data) Get. USBPoll. Buffer. In. Ptr(n) Get. USBPoll. Buffer. Out. Ptr(n) Get. USBState(n) • • • Set. USBInput. Buffer(data) Set. USBInput. Buffer. In. Ptr(n) Set. USBInput. Buffer. Out. Ptr(n) Set. USBOutput. Buffer(data) Set. USBOutput. Buffer. In. Ptr(n) Set. USBOutput. Buffer. Out. Ptr(n) Set. USBPoll. Buffer(data) Set. USBPoll. Buffer. In. Ptr(n) Set. USBPoll. Buffer. Out. Ptr(n) Set. USBState(n) • • • Get. HSInput. Buffer(data) Get. HSInput. Buffer. In. Ptr(n) Get. HSInput. Buffer. Out. Ptr(n) Get. HSOutput. Buffer(data) Get. HSOutput. Buffer. In. Ptr(n) Get. HSOutput. Buffer. Out. Ptr(n) Get. HSFlags(n) Get. HSSpeed(n) Get. HSState(n) • • • Set. HSInput. Buffer(data) Set. HSInput. Buffer. In. Ptr(n) Set. HSInput. Buffer. Out. Ptr(n) Set. HSOutput. Buffer(data) Set. HSOutput. Buffer. In. Ptr(n) Set. HSOutput. Buffer. Out. Ptr(n) Set. HSFlags(n) Set. HSSpeed(n) Set. HSState(n)

Compiler Usage • • • Extract compiler to the directory of your choice Open a command prompt or terminal window Execute NBC – – D: Bricxcc>nbc Next Byte Codes Compiler version 1. 0. 1. b 15 (1. 0. 1. 15, built Dec 19 2006 06: 25: 36) Copyright (c) 2006, John Hansen Use "nbc -help" for more information. D: Bricxcc>nbc –help Next Byte Codes Compiler version 1. 0. 1. b 15 (1. 0. 1. 15, built Dec 19 2006 06: 25: 36) Copyright (c) 2006, John Hansen Syntax: nbc [options] filename [options] -T=<target>: target must be NXT -S=<portname>: specify port name (COMn or usb), resource name, or alias -BT: use bluetooth -d: download program -b: treat input file as a binary file (don't compile it) -q: no sound upon download completion -x: decompile program -O=<outfile> : specify output file -E=<filename> : write compiler errors to <filename> -I=<path>: search <path> for include files -L=<filename> : generate code listing to <filename> -help : display command line options D: Bricxcc>nbc –S=usb –d testinc. nbc The previous command produced no output because there were no program errors and the download succeeded.
- Slides: 93