NXC_Guide
-
Upload
craciun-andreea -
Category
Documents
-
view
15 -
download
0
Transcript of NXC_Guide
-
5/26/2018 NXC_Guide
1/123
Not eXactly C(NXC)
Programmer's GuideVersion 1.0.1 b33
October 10, 2007
by John Hansen
-
5/26/2018 NXC_Guide
2/123
Page i
Contents
1 Introduction................................................................................................................. 12 The NXC Language .................................................................................................... 2
2.1 Lexical Rules ...................................................................................................... 2
2.1.1 Comments ................................................................................................... 22.1.2 Whitespace.................................................................................................. 22.1.3 Numerical Constants................................................................................... 32.1.4 Identifiers and Keywords............................................................................ 3
2.2 Program Structure............................................................................................... 32.2.1 Tasks ........................................................................................................... 32.2.2 Functions..................................................................................................... 42.2.3 Variables ..................................................................................................... 62.2.4 Structs ......................................................................................................... 72.2.5 Arrays.......................................................................................................... 8
2.3 Statements ........................................................................................................... 9
2.3.1 Variable Declaration................................................................................... 92.3.2 Assignment ............................................................................................... 102.3.3 Control Structures ..................................................................................... 102.3.4 The asm Statement.................................................................................... 132.3.5 Other Statements....................................................................................... 14
2.4 Expressions ....................................................................................................... 152.4.1 Conditions ................................................................................................. 16
2.5 The Preprocessor............................................................................................... 162.5.1 #include..................................................................................................... 162.5.2 #define....................................................................................................... 172.5.3 ## (Concatenation).................................................................................... 17
2.5.4 Conditional Compilation........................................................................... 173 NXC API................................................................................................................... 183.1 General Features ............................................................................................... 18
3.1.1 Timing Functions ...................................................................................... 183.1.2 Program Control Functions....................................................................... 193.1.3 String Functions ........................................................................................ 213.1.4 Array Functions ........................................................................................ 223.1.5 Numeric Functions.................................................................................... 233.1.6 Low-level System Functions..................................................................... 24
3.2 Input Module..................................................................................................... 423.2.1 Types and Modes ...................................................................................... 43
3.2.2 Sensor Information.................................................................................... 463.2.3 IOMap Offsets .......................................................................................... 493.3 Output Module.................................................................................................. 49
3.3.1 Convenience Calls .................................................................................... 533.3.2 Primitive Calls .......................................................................................... 583.3.3 IOMap Offsets .......................................................................................... 60
3.4 IO Map Addresses............................................................................................. 613.5 Sound Module................................................................................................... 62
-
5/26/2018 NXC_Guide
3/123
Page ii
3.5.1 High-level functions.................................................................................. 623.5.2 Low-level functions .................................................................................. 633.5.3 IOMap Offsets .......................................................................................... 65
3.6 IOCtrl Module................................................................................................... 663.6.1 IOMap Offsets .......................................................................................... 66
3.7 Display module................................................................................................. 663.7.1 High-level functions.................................................................................. 673.7.2 Low-level functions .................................................................................. 683.7.3 IOMap Offsets .......................................................................................... 70
3.8 Loader Module.................................................................................................. 703.8.1 IOMap Offsets .......................................................................................... 75
3.9 Command Module ............................................................................................ 753.9.1 IOMap Offsets .......................................................................................... 75
3.10 Button Module .................................................................................................. 753.10.1 High-level functions.................................................................................. 763.10.2 Low-level functions .................................................................................. 76
3.10.3 IOMap Offsets .......................................................................................... 783.11 UI Module......................................................................................................... 783.11.1 IOMap Offsets .......................................................................................... 82
3.12 LowSpeed Module............................................................................................ 833.12.1 High-level functions.................................................................................. 843.12.2 Low-level functions .................................................................................. 863.12.3 IOMap Offsets .......................................................................................... 90
3.13 Comm Module .................................................................................................. 903.13.1 High-level functions.................................................................................. 913.13.2 Low-level functions .................................................................................. 953.13.3 IOMap Offsets ........................................................................................ 105
3.14 HiTechnic API Functions ............................................................................... 1063.15 Mindsensors API Functions............................................................................ 117
-
5/26/2018 NXC_Guide
4/123
Page iii
Tables
Table 1. NXC Keywords..................................................................................................... 3Table 2. Variable Types...................................................................................................... 6Table 3. Operators............................................................................................................. 10
Table 4. ASM Keywords .................................................................................................. 14Table 5. Expressions......................................................................................................... 15Table 6. Conditions........................................................................................................... 16Table 7. Input Module Constants...................................................................................... 42Table 8. Sensor Type Constants........................................................................................ 43Table 9. Sensor Mode Constants ...................................................................................... 43Table 10. Sensor Configuration Constants ....................................................................... 44Table 11. Sensor Field Constants...................................................................................... 44Table 12. Input Module IOMap Offsets ........................................................................... 49Table 13. Output Module Constants ................................................................................. 49Table 14. Output Field Constants ..................................................................................... 52
Table 15. UpdateFlag Constants....................................................................................... 53Table 16. OutputMode Constants ..................................................................................... 53Table 17. RunState Constants........................................................................................... 53Table 18. RegMode Constants.......................................................................................... 53Table 19. Reset Constants................................................................................................. 54Table 20. Output Port Constants....................................................................................... 54Table 21. Output Module IOMap Offsets......................................................................... 61Table 22. IOMA Constants............................................................................................... 61Table 23. Sound Module Constants.................................................................................. 62Table 24. Sound Flags Constants...................................................................................... 63Table 25. Sound State Constants ...................................................................................... 63
Table 26. Sound Mode Constants ..................................................................................... 63Table 27. Miscellaneous Sound Constants ....................................................................... 64Table 28. Sound Module IOMap Offsets.......................................................................... 65Table 29. IOCtrl Module Constants.................................................................................. 66Table 30. IOCtrl Module IOMap Offsets ......................................................................... 66Table 31. Display Module Constants................................................................................ 66Table 32. Display Flags Constants.................................................................................... 68Table 33. Display Module IOMap Offsets ....................................................................... 70Table 34. Loader Module Constants................................................................................. 71Table 35. Loader Result Codes......................................................................................... 71Table 36. Loader Module IOMap Offsets......................................................................... 75
Table 37. Command Module Constants............................................................................ 75Table 38. Command Module IOMap Offsets ................................................................... 75Table 39. Button Module Constants ................................................................................. 75Table 40. Button Constants............................................................................................... 76Table 41. Button State Constants...................................................................................... 76Table 42. Button Module IOMap Offsets ......................................................................... 78Table 43. UI Module Constants........................................................................................ 78Table 44. UI Command Flags Constants .......................................................................... 79
-
5/26/2018 NXC_Guide
5/123
Page iv
Table 45. UI State Constants ............................................................................................ 79Table 46. UI Button Constants.......................................................................................... 79Table 47. UI Bluetooth State Constants............................................................................ 79Table 48. UI Module IOMap Offsets................................................................................ 83Table 49. LowSpeed Module Constants ........................................................................... 83
Table 50. Lowspeed (I2C) Return Value Constants ......................................................... 84Table 51. Low Speed State Constants............................................................................... 86Table 52. Low Speed Channel State Constants ................................................................ 86Table 53. Low Speed Mode Constants ............................................................................. 86Table 54. Low Speed Error Type Constants..................................................................... 87Table 55. LowSpeed Module IOMap Offsets................................................................... 90Table 56. Comm Module Constants ................................................................................. 90Table 57. Comm Miscellaneous Constants....................................................................... 95Table 58. Comm BtState Constants.................................................................................. 96Table 59. Comm BtStateStatus Constants ........................................................................ 96Table 60. Comm BtHwStatus Constants .......................................................................... 96
Table 61. Comm HsFlags Constants................................................................................. 96Table 62. Comm HsState Constants ................................................................................. 96Table 63. Comm DeviceStatus Constants......................................................................... 96Table 64. Comm Module Interface Constants .................................................................. 97Table 65. Comm Module IOMap Offsets ....................................................................... 106
-
5/26/2018 NXC_Guide
6/123
NXC Programmer's Guide
Page 1
1 IntroductionNXC stands for Not eXactly C. It is a simple language for programming the LEGOMINDSTORMS NXT product. The NXT has a bytecode interpreter (provided byLEGO), which can be used to execute programs. The NXC compiler translates a source
program into NXT bytecodes, which can then be executed on the target itself. Althoughthe preprocessor and control structures of NXC are very similar to C, NXC is not ageneral-purpose programming language - there are many restrictions that stem fromlimitations of the NXT bytecode interpreter.
Logically, NXC is defined as two separate pieces. The NXC language describes thesyntax to be used in writing programs. The NXC Application Programming Interface(API) describes the system functions, constants, and macros that can be used byprograms. This API is defined in a special file known as a "header file" which is, bydefault, automatically included when compiling a program.
This document describes both the NXC language and the NXC API. In short, it provides
the information needed to write NXC programs. Since there are different interfaces forNXC, this document does not describe how to use any specific NXC implementation(such as the command-line compiler or Bricx Command Center). Refer to thedocumentation provided with the NXC tool, such as theNXC User Manual, forinformation specific to that implementation.
For up-to-date information and documentation for NXC, visit the NXC website athttp://bricxcc.sourceforge.net/nxc/.
-
5/26/2018 NXC_Guide
7/123
NXC Programmer's Guide
Page 2
2 The NXC LanguageThis section describes the NXC language itself. This includes the lexical rules used bythe compiler, the structure programs, statements, and expressions, and the operation ofthe preprocessor.
NXC is a case-sensitive language just like C and C++. That means that the identifier"xYz" is not the same identifier as "Xyz". Similarly, the "if" statement begins with thekeyword "if" but "iF", "If", or "IF" are all just valid identifiers not keywords.
2.1 Lexical RulesThe lexical rules describe how NXC breaks a source file into individual tokens. Thisincludes the way comments are written, the handling of whitespace, and valid charactersfor identifiers.
2.1.1 CommentsTwo forms of comments are supported in NXC. The first form (traditional C comments)begin with / * and end with */ . They may span multiple lines, but do not nest:
/ * t hi s i s a comment */
/ * t hi s i s a two l i ne comment */
/ * another comment . . . / * t ryi ng t o nest. . . endi ng the i nner comment . . . */
t hi s text i s no l onger a comment ! */
The second form of comments begins with / / and ends with a newline (sometimesknown as C++ style comments).
/ / a si ngl e l i ne comment
The compiler ignores comments. Their only purpose is to allow the programmer todocument the source code.
2.1.2 WhitespaceWhitespace (spaces, tabs, and newlines) is used to separate tokens and to make programs
more readable. As long as the tokens are distinguishable, adding or subtractingwhitespace has no effect on the meaning of a program. For example, the following linesof code both have the same meaning:
x=2;x = 2 ;
Some of the C++ operators consist of multiple characters. In order to preserve thesetokens whitespace must not be inserted within them. In the example below, the first line
-
5/26/2018 NXC_Guide
8/123
NXC Programmer's Guide
Page 3
uses a right shift operator ('>>'), but in the second line the added space causes the '>'symbols to be interpreted as two separate tokens and thus generate an error.
x = 1 >> 4; / / set x t o 1 r i ght shi f t ed by 4 bi t s
x = 1 > > 4; / / err or
2.1.3 Numerical ConstantsNumerical constants may be written in either decimal or hexadecimal form. Decimalconstants consist of one or more decimal digits. Hexadecimal constants start with 0xor0Xfollowed by one or more hexadecimal digits.
x = 10; / / set x t o 10x = 0x10; / / set x to 16 ( 10 hex)
2.1.4 Identifiers and KeywordsIdentifiers are used for variable, task, function, and subroutine names. The first characterof an identifier must be an upper or lower case letter or the underscore ('_'). Remainingcharacters may be letters, numbers, and an underscore.
A number of potential identifiers are reserved for use in the NXC language itself. Thesereserved words are call keywords and may not be used as identifiers. A complete list ofkeywords appears below:
__RETURN____RETVAL____STRRETVAL____TMPBYTE____TMPWORD__
__TMPLONG__absasmboolbreakbytecase
charconstcont i nuedef aul tdo
el sef al sef orgot oi fi nl i nei nt
l ongmut expr i or i t yr epeatreturn
saf ecal lshor tsi gnstartstopst r i ngstruct
subswi t chtasktruet ypedef
unsi gnedunt i lvoi dwhi l e
Table 1. NXC Keywords
2.2 Program StructureAn NXC program is composed of code blocks and variables. There are two distinct typesof code blocks: tasks and functions. Each type of code block has its own unique features,but they share a common structure.
2.2.1 TasksThe NXT supports multi-threading, so a task in NXC directly corresponds to an NXTthread. Tasks are defined using the taskkeyword using the following syntax:
-
5/26/2018 NXC_Guide
9/123
NXC Programmer's Guide
Page 4
t ask name( ){ / / t he t ask' s code i s pl aced here}
The name of the task may be any legal identifier. A program must always have at least
one task - named "main" - which is started whenever the program is run. The maximumnumber of tasks is 256.
The body of a task consists of a list of statements. Scheduling dependant tasks using thePrecedes or Follows API function is the primary mechanism supported by the NXT forstarting other tasks concurrently. Tasks may also be started and stopped using the startand stopstatements. There is also an NXC API command, St opAl l Tasks, which stopsall currently running tasks. You can also stop all tasks using the Stop function. A task canstop itself via the ExitTo function or by task execution simply reaching the end of thetask.
2.2.2 FunctionsIt is often helpful to group a set of statements together into a single function, which canthen be called as needed. NXC supports functions with arguments and return values.Functions are defined using the following syntax:
[safecall] [inline] return_type name(argument_list){
/ / body of t he f unct i on}
The return type should be the type of data returned. In the C programming language,functions are specified with the type of data they return. Functions that do not return data
are specified to returnvoi d
.The argument list may be empty, or may contain one or more argument definitions. Anargument is defined by its typefollowed by its name. Commas separate multiplearguments. All values are represented as bool, char, byte, int, short, long, unsigned int,unsigned long, strings, struct types, or arrays of any type. NXC also supports passingargument types by value, by constant value, by reference, and by constant reference.
When arguments are passed by value from the calling function to the callee the compilermust allocate a temporary variable to hold the argument. There are no restrictions on thetype of value that may be used. However, since the function is working with a copy of theactual argument, the caller will not see any changes it makes to the value. In the examplebelow, the function f ooattempts to set the value of its argument to 2. This is perfectlylegal, but since f oois working on a copy of the original argument, the variable yfrommain task remains unchanged.
-
5/26/2018 NXC_Guide
10/123
NXC Programmer's Guide
Page 5
voi d f oo( i nt x){
x = 2;}
task mai n( )
{i nt y = 1; / / y i s now equal to 1f oo( y) ; / / y i s st i l l equal t o 1!
}
The second type of argument, const arg_type, is also passed by value, but with therestriction that only constant values (e.g. numbers) may be used. This is rather importantsince there are a few NXT functions that only work with constant arguments.
voi d f oo(const i nt x){
Pl aySound( x) ; / / okx = 1; / / error - cannot modi f y argument
}
task mai n( ){
f oo( 2) ; / / okf oo(4*5) ; / / ok - expressi on i s sti l l constantfoo(x) ; / / er ror - x i s not a constant
}
The third type, arg_type &, passes arguments by reference rather than by value. Thisallows the callee to modify the value and have those changes visible in the caller.However, only variables may be used when calling a function using arg_type &
arguments:voi d f oo( i nt &x){
x = 2;}
task mai n( ){
i nt y = 1; / / y i s equal to 1
f oo( y) ; / / y i s now equal t o 2foo(2) ; / / er ror - onl y var i abl es al l owed
}
The fourth type, const arg_type &, is rather unusual. It is also passed by reference,but with the restriction that the callee is not allowed to modify the value. Because of thisrestriction, the compiler is able to pass anything (not just variables) to functions usingthis type of argument. In general this is the most efficient way to pass arguments in NXC.
Functions must be invoked with the correct number (and type) of arguments. Theexample below shows several different legal and illegal calls to function f oo:
-
5/26/2018 NXC_Guide
11/123
NXC Programmer's Guide
Page 6
voi d f oo( i nt bar , const i nt baz){
/ / do somethi ng here. . .}
task mai n( )
{i nt x; / / decl are var i abl e x
f oo( 1, 2) ; / / okf oo( x, 2) ; / / okf oo( 2, x) ; / / er ror - 2nd argument not constant !f oo( 2) ; / / err or - wrong number of argument s!
}
NXC functions may optionally be marked as inline functions. This means that each callto a function will result in another copy of the function's code being included in theprogram. Unless used judiciously, inline functions can lead to excessive code size.
If a function is not marked as inline then an actual NXT subroutine is created and the callto the function in NXC code will result in a subroutine call to the NXT subroutine. Thetotal number of non-inline functions (aka subroutines) and tasks must not exceed 256.
Another optional keyword that can be specified prior to the return type of a function isthe safecall keyword. If a function is marked as safecall then the compiler willsynchronize the execution of this function across multiple threads by wrapping each callto the function in Acquire and Release calls. If a second thread tries to call a safecallfunction while another thread is executing it the second thread will have to wait until thefunction returns to the first thread.
2.2.3 VariablesAll variables in NXC are of the following types:
Type Name Information
bool 8 bit unsignedbyte, unsigned char 8 bit unsignedchar 8 bit signed unsigned int 16 bit unsigned short, int 16 bit signed unsigned long 32 bit unsigned long 32 bit signed
mutex Special type used for exclusive code accessstring Array of bytestruct User-defined structure typesArrays Arrays of any type
Table 2. Variable Types
Variables are declared using the keyword for the desired type followed by a comma-separated list of variable names and terminated by a semicolon ('; '). Optionally, an initial
-
5/26/2018 NXC_Guide
12/123
NXC Programmer's Guide
Page 7
value for each variable may be specified using an equals sign ('=') after the variablename. Several examples appear below:
i nt x; / / decl are xbool y, z; / / decl are y and zl ong a=1, b; / / decl are a and b, i ni t i al i ze a t o 1
Global variables are declared at the program scope (outside of any code block). Oncedeclared, they may be used within all tasks, functions, and subroutines. Their scopebegins at declaration and ends at the end of the program.
Local variables may be declared within tasks and functions. Such variables are onlyaccessible within the code block in which they are defined. Specifically, their scopebegins with their declaration and ends at the end of their code block. In the case of localvariables, a compound statement (a group of statements bracketed by '{' and '}') isconsidered a block:
i nt x; / / x i s gl obal
t ask mai n( ){
i nt y; / / y i s l ocal t o t ask mai nx = y; / / ok{ / / begi n compound statement
i nt z; / / l ocal z decl aredy = z; / / ok
}y = z; / / er ror - z no l onger i n scope
}
task f oo( )
{ x = 1; / / oky = 2; / / er ror - y i s not gl obal
}
2.2.4 StructsNXC supports user-defined aggregate types known as structs. These are declared verymuch like you declare structs in a C program.
struct car{ st r i ng car_t ype; i nt manu_year ;};
struct person{ st r i ng name; i nt age; car vehi cl e;};
-
5/26/2018 NXC_Guide
13/123
NXC Programmer's Guide
Page 8
myType f red = 23;person myPerson;
After you have defined the structure type you can use the new type to declare a variableor nested within another structure type declaration. Members (or fields) within the struct
are accessed using a dot notation. myPerson. age = 40;
anotherPerson = myPerson;
f ooBar . car_t ype = "honda"; f ooBar. manu_year = anotherPerson. age;
You can assign structs of the same type but the compiler will complain if the types do notmatch.
2.2.5 ArraysNXC also support arrays. Arrays are declared the same way as ordinary variables, butwith an open and close bracket following the variable name.
i nt my_array[] ; / / decl are an ar ray wi th 0 el ement s
To declare arrays with more than one dimension simply add more pairs of squarebrackets. The maximum number of dimensions supported in NXC is 4.
bool my_ar ray[ ] [ ] ; / / decl are a 2- di mensi onal array
Global arrays with one dimension can be initialized at the point of declaration using thefollowing syntax:
i nt X[ ] = {1, 2, 3, 4}, Y[ ] ={10, 10}; / / 2 ar raysThe elements of an array are identified by their position within the array (called anindex). The first element has an index of 0, the second has index 1, etc. For example:
my_arr ay[0] = 123; / / set f i rst el ement t o 123
my_arr ay[1] = my_arr ay[2] ; / / copy thi rd i nto second
Currently there are some limitations on how arrays can be used. Some of these limitationswill likely be removed in future versions of NXC.
To initialize local arrays or arrays with multiple dimensions it is necessary to use theArrayInit function. The following example shows how to initialize a two-dimensional
array using ArrayInit. It also demonstrates some of the supported array API functions andexpressions.
t ask mai n( ){ i nt myAr ray[ ] [ ] ; i nt myVector [ ] ; byte f ooArray[ ] [ ] [ ] ;
Ar rayI ni t ( myVector , 0, 10) ; / / 10 zeros i n myVector
-
5/26/2018 NXC_Guide
14/123
NXC Programmer's Guide
Page 9
Ar rayI ni t ( myArray, myVector, 10) ; / / 10 vectors myArray Ar rayI ni t ( f ooArray, myArray, 2) ; / / 2 myArrays i n f ooArray
myVector = myArray[ 1] ; / / okay as of b25 f ooArray[1] = myArray; / / okay as of b25 myVector[ 4] = 34;
myArray[ 1] = myVector; / / okay as of b25
i nt ax[] , ay[ ] ; Ar rayBui l d( ax, 5, 6) ; Ar rayBui l d( ay, 2, 10, 6, 43) ; i nt axl en = ArrayLen( ax) ; Ar raySubset ( ax, ay, 1, 2) ; / / ax = {10, 6} i f ( ax == ay) { / / arr ay compar i sons suppor t ed as of b25 }}
NXC also supports specifying an initial size for both global and local arrays. The
compiler automatically generates the required code to correctly initialize the array tozeros. If a global array declaration includes both a size and a set of initial values the sizeis ignored in favor of the specified values.
t ask mai n( ){ i nt myAr ray[10] [ 10] ; i nt myVector[ 10] ;
/ / Ar rayI ni t ( myVector , 0, 10) ; / / 10 zeros i n myVector/ / Ar rayI ni t ( myArray, myVector , 10) ; / / 10 vectors myArray
/ *
The cal l s t o Ar rayI ni t are not requi red si nce we speci f i ed t he equi val ent i ni t i al si zes above. I n fact , t he myVector ar ray i s not needed unl ess we have a use f or i t other than t o i ni t i al i ze myArray.*/}
2.3 StatementsThe body of a code block (task or function) is composed of statements. Statements areterminated with a semi-colon ('; ').
2.3.1 Variable DeclarationVariable declaration, as described in the previous section, is one type of statement. Itdeclares a local variable (with optional initialization) for use within the code block. Thesyntax for a variable declaration is:
i nt variables;
where variables is a comma separated list of names with optional initial value:
-
5/26/2018 NXC_Guide
15/123
NXC Programmer's Guide
Page 10
name[ =expression]
Arrays of variables may also be declared:
i nt array[ n] [ =i ni t i al i zer f or gl obal one- di mensi on ar rays] ;
2.3.2 AssignmentOnce declared, variables may be assigned the value of an expression:
variable assign_operator expression;
There are nine different assignment operators. The most basic operator, '=', simplyassigns the value of the expression to the variable. The other operators modify thevariable's value in some other way as shown in the table below
Operator Action
= Set variable to expression+= Add expression to variable-= Subtract expression from variable
*= Multiple variable by expression/= Divide variable by expression%= Set variable to remainder after dividing by expression&= Bitwise AND expression into variable|= Bitwise OR expression into variable^= Bitwise exclusive OR into variable||= Set variable to absolute value of expression+-= Set variable to sign (-1,+1,0) of expression>>= Right shift variable by expression
-
5/26/2018 NXC_Guide
16/123
NXC Programmer's Guide
Page 11
The i fstatement evaluates a condition. If the condition is true it executes one statement(the consequence). An optional second statement (the alternative) is executed if thecondition is false. The two syntaxes for an i f statement is shown below.
i f (condition) consequencei f (condition) consequence el se alternative
Note that the condition is enclosed in parentheses. Examples are shown below. Note howa compound statement is used in the last example to allow two statements to be executedas the consequence of the condition.
i f ( x==1) y = 2;i f ( x==1) y = 3; el se y = 4;i f ( x==1) { y = 1; z = 2; }
The whi l estatement is used to construct a conditional loop. The condition is evaluated,and if true the body of the loop is executed, then the condition is tested again. Thisprocess continues until the condition becomes false (or a breakstatement is executed).The syntax for a whi l eloop appears below:
whi l e (condition) body
It is very common to use a compound statement as the body of a loop:
whi l e( x < 10){
x = x+1;y = y*2;
}
A variant of the whi l eloop is the do-whi l eloop. Its syntax is:
do body whi l e (condition)
The difference between a whi l eloop and a do-whi l e loop is that the do-whi l eloopalways executes the body at least once, whereas the whi l eloop may not execute it at all.
Another kind of loop is the f or loop:
for(stmt1 ; condition ; stmt2) body
A f or loop always executes stmt1, then it repeatedly checks the condition and while itremains true executes the body followed by stmt2. The f or loop is equivalent to:
stmt1;whi l e(condition){
body
stmt2;}
The r epeat statement executes a loop a specified number of times:
repeat (expression) body
The expression determines how many times the body will be executed. Note: It is onlyevaluated a single time and then the body is repeated that number of times. This is
-
5/26/2018 NXC_Guide
17/123
NXC Programmer's Guide
Page 12
different from both the whi l eand do-whi l eloops which evaluate their condition eachtime through the loop.
A swi t chstatement can be used to execute one of several different blocks of codedepending on the value of an expression. One or more case labels precede each block ofcode. Each case must be a constant and unique within the switch statement. The switch
statement evaluates the expression then looks for a matching case label. It will thenexecute any statements following the matching case until either a break statement or theend of the switch is reached. A single def aul t label may also be used - it will match anyvalue not already appearing in a case label. Technically, a switch statement has thefollowing syntax:
swi t ch (expression) body
The case and default labels are not statements in themselves - they are labelsthat precedestatements. Multiple labels can precede the same statement. These labels have thefollowing syntax
case constant_expression :def aul t :
A typical switch statement might look like this:
swi t ch( x){
case 1:/ / do somethi ng when X i s 1break;
case 2:case 3:
/ / do somethi ng el se when x i s 2 or 3break;
def aul t :/ / do t hi s when x i s not 1, 2, or 3break;
}
NXC also supports using string types in the switch expression and constant strings in caselabels.
The gotostatement forces a program to jump to the specified location. Statements in aprogram can be labeled by preceding them with an identifier and a colon. A gotostatement then specifies the label that the program should jump to. For example, this is
how an infinite loop that increments a variable could be implemented using got o:my_l oop:
x++;goto my_l oop;
The gotostatement should be used sparingly and cautiously. In almost every case,control structures such as i f, whi l e, and swi t chmake a program much more readableand maintainable than using got o.
-
5/26/2018 NXC_Guide
18/123
NXC Programmer's Guide
Page 13
NXC also defines the unt i l macro which provides a convenient alternative to thewhi l eloop. The actual definition of unt i l is:
#def i ne unti l (c) whi l e( !( c))
In other words, unt i l will continue looping until the condition becomes true. It is most
often used in conjunction with an empty body statement:unt i l ( SENSOR_1 == 1) ; / / wai t f or sensor t o be pressed
2.3.4 The asm StatementThe asmstatement is used to define many of the NXC API calls. The syntax of thestatement is:
asm{one or more lines of assembly language
}
The statement simply emits the body of the statement as NeXT Byte Codes (NBC) codeand passes it directly to the NBC compiler backend. The asm statement can often be usedto optimize code so that it executes as fast as possible on the NXT firmware. Thefollowing example shows an asm block containing variable declarations, labels, and basicNBC statements as well as comments.
asm{/ / j mp __l bl 00D5 dseg segment sl 0000 sl ong sl 0005 sl ong bGTTrue byte dseg ends
mov sl 0000, 0x0 mov sl 0005, sl 0000 mov sl 0000, 0x1 cmp GT, bGTTrue, sl 0005, sl 0000 set bGTTrue, FALSE br t st EQ, __l bl 00D5, bGTTrue __ l bl 00D5:}
A few NXC keywords have meaning only within an asm statement. These keywordsprovide a means for returning string or scalar values from asm statements and for usingtemporary integer variables of byte, word, and long sizes.
ASM Keyword Meaning__RETURN__ Used to return a value other than __RETVAL__ or
__STRRETVAL____RETVAL__ Writing to this 4-byte value returns it to the calling program__STRRETVAL__ Writing to this string value returns it to the calling program__TMPBYTE__ Use this temporary variable to write and return single byte values__TMPWORD__ Use this temporary variable to write and return 2-byte values__TMPLONG__ Use this temporary variable to write and return 4-byte values
-
5/26/2018 NXC_Guide
19/123
NXC Programmer's Guide
Page 14
Table 4. ASM Keywords
The asm block statement and these special ASM keywords are used throughout the NXCAPI. See the NXCDefs.h header file for several examples of how they can be put to use.To keep the main NXC code as "C-like" as possible and for the sake of better readabilityNXC asm block statements can be wrapped in preprocessor macros and placed in custom
header files which are included using #include. The following example demonstratesusing macro wrappers around asm block statements.
#def i ne SetMotorSpeed( por t , cc, t hresh, f ast , sl ow) \ asm{ \ set t heSpeed, f ast \ br cmp cc, EndI f Out__I __, SV, t hresh \ set theSpeed, sl ow \EndI f Out __I __: \ OnFwd( port , t heSpeed) \ __I ncI __ \}
2.3.5 Other StatementsA function call is a statement of the form:
name(arguments) ;
The arguments list is a comma-separated list of expressions. The number and type ofarguments supplied must match the definition of the function itself.
Tasks may be started or stopped with the following statements.
start task_name;
st op task_name;
You can adjust the priority of a task using the priority statement.
pri ori ty task_name, new_priority;
Within loops (such as a whi l eloop) the breakstatement can be used to exit the loopand the cont i nuestatement can be used to skip to the top of the next iteration of theloop. The break statement can also be used to exit a switch statement.
break;
cont i nue;
It is possible to cause a function to return before it reaches the end of its code using the
returnstatement with an optional return value.return [expressi on] ;
Many expressions are not legal statements. One notable exception is expressionsinvolving the increment (++) or decrement (- - ) operators.
x++;
The empty statement (just a bare semicolon) is also a legal statement.
-
5/26/2018 NXC_Guide
20/123
NXC Programmer's Guide
Page 15
2.4 ExpressionsValuesare the most primitive type of expressions. More complicated expressions areformed from values using various operators. The NXC language only has two built inkinds of values: numerical constants and variables.
Numerical constants in the NXT are represented as integers. The type depends on thevalue of the constant. NXC internally uses 32 bit signed math for constant expressionevaluation. Numeric constants can be written as either decimal (e.g. 123) or hexadecimal(e.g. 0xABC). Presently, there is very little range checking on constants, so using a valuelarger than expected may have unusual effects.
Two special values are predefined: trueand f al se. The value of f al seis zero (0),while the value of trueis one (1). The same values hold for relational operators (e.g.
-
5/26/2018 NXC_Guide
21/123
NXC Programmer's Guide
Page 16
Where needed, parentheses may be used to change the order of evaluation:
x = 2 + 3 * 4; / / set x t o 14y = (2 + 3) * 4; / / set y to 20
2.4.1 ConditionsComparing two expressions forms a condition. There are also two constant conditions -trueand f al se - that always evaluate to true or false respectively. A condition may benegated with the negation operator, or two conditions combined with the AND and ORoperators. The table below summarizes the different types of conditions.
Condition Meaning
true always true
f al se always false
Expr true if expr is not equal to 0
Expr 1 == expr 2 true if expr1 equals expr2
Expr 1 ! = expr 2 true if expr1 is not equal to expr2
Expr1 < expr2 true if one expr1 is less than expr2
Expr 1 expr2 true if expr1 is greater than expr2
Expr 1 >= expr 2 true if expr1 is greater than or equal to expr2
! condi t i on logical negation of a condition - true if condition is false
Cond1 && cond2 logical AND of two conditions (true if and only if both conditions aretrue)
Cond1 | | cond2 logical OR of two conditions (true if and only if at least one of theconditions are true)
Table 6. Conditions
2.5 The PreprocessorThe preprocessor implements the following directives: #i ncl ude, #def i ne, #i f def,#i f ndef, #endi f, #i f, #el i f, #undef , ##, #l i ne, and #pr agma. Itsimplementation is fairly close to a standard C preprocessor, so most things that work in ageneric C preprocessor should have the expected effect in NXC. Significant deviationsare listed below.
2.5.1 #includeThe #i ncl udecommand works as expected, with the caveat that the filename must beenclosed in double quotes. There is no notion of a system include path, so enclosing afilename in angle brackets is forbidden.
-
5/26/2018 NXC_Guide
22/123
NXC Programmer's Guide
Page 17
#include "foo.h" // ok#include // error!
NXC programs can begin with #i ncl ude "NXCDef s. h" but they don't need to. Thisstandard header file includes many important constants and macros which form the coreNXC API. Current versions of NXC no longer require that you manually include the
NXCDefs.h header file. Unless you specifically tell the compiler to ignore the standardsystem files this header file will automatically be included for you.
2.5.2 #defineThe #def i necommand is used for simple macro substitution. Redefinition of a macro isan error. The end of the line normally terminates macros, but the newline may be escapedwith the backslash ('\ ') to allow multi-line macros:
#def i ne f oo( x) do { bar ( x) ; \ baz(x) ; } whi l e( f al se)
The #undefdirective may be used to remove a macros definition.
2.5.3 ## (Concatenation)The ##directive works similar to the C preprocessor. It is replaced by nothing, whichcauses tokens on either side to be concatenated together. Because it acts as a separatorinitially, it can be used within macro functions to produce identifiers via combinationwith parameter values.
2.5.4 Conditional Compilation
Conditional compilation works similar to the C preprocessor. The following preprocessordirectives may be used:
#i f def symbol#i f ndef symbol#el se#endi f#i f condition#el i f
-
5/26/2018 NXC_Guide
23/123
NXC Programmer's Guide
Page 18
3 NXC APIThe NXC API defines a set of constants, functions, values, and macros that provideaccess to various capabilities of the NXT such as sensors, outputs, and communication.
The API consists of functions, values, and constants. A function is something that can becalled as a statement. Typically it takes some action or configures some parameter.Values represent some parameter or quantity and can be used in expressions. Constantsare symbolic names for values that have special meanings for the target. Often, a set ofconstants will be used in conjunction with a function.
3.1 General Features
3.1.1 Timing Functions
Wait(time) FunctionMake a task sleep for specified amount of time (in 1000ths of a second). The timeargument may be an expression or a constant:
Wai t ( 1000) ; / / wai t 1 secondWai t ( Random( 1000) ) ; / / wai t randomt i me up t o 1 second
CurrentTick() Value
Return an unsigned 32-bit value, which is the current system timing value (called a"tick") in milliseconds.
x = CurrentTi ck( ) ;
FirstTick() Value
Return an unsigned 32-bit value, which is the system timing value (called a "tick") inmilliseconds at the time that the program began running.
x = Fi rstTi ck() ;
SleepTime() Value
Return the number of minutes that the NXT will remain on before it automaticallyshuts down.
x = Sl eepTi me( ) ;
SleepTimer() Value
Return the number of minutes left in the countdown to zero from the originalSleepTime value. When the SleepTimer value reaches zero the NXT will shutdown.
x = Sl eepTi mer( ) ;
-
5/26/2018 NXC_Guide
24/123
NXC Programmer's Guide
Page 19
ResetSleepTimer() Function
Reset the system sleep timer back to the SleepTime value. Executing this functionperiodically can keep the NXT from shutting down while a program is running.
ResetSl eepTi mer( ) ;
SetSleepTime(minutes) Function
Set the NXT sleep timeout value to the specified number of minutes.
SetSl eepTi me(8) ;
SleepNow() Function
Turn off the NXT immediately.
Sl eepNow( ) ;
SetSleepTimer(minutes) Function
Set the system sleep timer to the specified number of minutes.
SetSl eepTi mer( 3) ;
3.1.2 Program Control Functions
Stop(bvalue) Function
Stop the running program if bvalue is true. This will halt the program completely, soany code following this command will be ignored.
Stop( x == 24) ; / / st op the programi f x==24
StopAllTasks() Function
Stop all currently running tasks. This will halt the program completely, so any codefollowing this command will be ignored.
StopAl l Tasks( ) ; / / stop the program
StartTask(task) Function
Start the specified task.
Star tTask( sound) ; / / st ar t t he sound t ask
StopTask(task) Function
Stop the specified task. This requires the enhanced NBC/NXC firmware.
StopTask(sound) ; / / st op the sound task
-
5/26/2018 NXC_Guide
25/123
NXC Programmer's Guide
Page 20
Acquire(mutex) Function
Acquire the specified mutex variable. If another task already has acquired the mutexthen the current task will be suspended until the mutex is released by the other task.This function is used to ensure that the current task has exclusive access to a sharedresource, such as the display or a motor. After the current task has finished using theshared resource the program should call Release to allow other tasks to acquire themutex.
Acqui re(motorMutex) ; / / make sure we have excl usi ve access/ / use the motorsRel ease(motorMutex);
Release(mutex) Function
Release the specified mutex variable. Use this to relinquish a mutex so that it can beacquired by another task. Release should always be called after a matching call toAcquire and as soon as possible after a shared resource is no longer needed.
Acqui re(motorMutex) ; / / make sure we have excl usi ve access/ / use the motorsRel ease(motorMutex); / / rel ease mutex f or other tasks
Precedes(task1, task2, ..., taskN) Function
Schedule the specified tasks for execution once the current task has completedexecuting. The tasks will all execute simultaneously unless other dependenciesprevent them from doing so. Generally this function should be called once within atask preferably at the start of the task definition.
Precedes( movi ng, drawi ng, pl ayi ng) ;
Follows(task1, task2, ..., taskN) Function
Schedule this task to follow the specified tasks so that it will execute once any of thespecified tasks has completed executing. Generally this function should be calledonce within a task preferably at the start of the task definition. If multiple tasksdeclare that they follow the same task then they will all execute simultaneously unlessother dependencies prevent them from doing so.
Fol l ows( mai n) ;
ExitTo(task) Function
Immediately exit the current task and start executing the specified task.Exi t To( nextTask) ;
-
5/26/2018 NXC_Guide
26/123
NXC Programmer's Guide
Page 21
3.1.3 String Functions
StrToNum(str) Value
Return the numeric value specified by the string passed to the function. If the contentof the string is not a numeric value then this function returns zero.
x = St rToNum( st rVal ) ;
StrLen(str) Value
Return the length of the specified string. The length of a string does not include thenull terminator at the end of the string.
x = St rLen( msg) ; / / return t he l ength of msg
StrIndex(str, idx) Value
Return the numeric value of the character in the specified string at the specified
index.x = St r I ndex( msg, 2) ; / / ret urn t he val ue of msg[2]
NumToStr(value) Value
Return the string representation of the specified numeric value.
msg = NumToSt r ( - 2) ; / / returns "- 2" i n a st r i ng
FormatNum(fmtstr, value) Value
Return the formatted string using the format and value. Use standard numeric sprintfformat specifiers within the format string.
msg = FormatNum( "val ue = %d", x) ;
StrCat(str1, str2, ..., strN) Value
Return a string which is the result of concatenating all of the string argumentstogether.
msg = St rCat ( "t est", "pl ease") ; / / returns "t estpl ease"
SubStr(string, idx, len) Value
Return a sub-string from the specified input string starting at idx and including the
specified number of characters.msg = SubSt r ( "t est", 1, 2) ; / / ret urns "es"
StrReplace(string, idx, newStr) Value
Return a string with the part of the string replaced (starting at the specified index)with the contents of the new string value provided in the third argument.
msg = St rRepl ace( "t est i ng", 3, "xx") ; / / returns "t esxxng"
-
5/26/2018 NXC_Guide
27/123
NXC Programmer's Guide
Page 22
Flatten(value) Value
Return a string containing the byte representation of the specified value.
msg = Fl at t en( 48) ; / / returns "0" si nce 48 == asci i ( "0")
msg = Fl at t en( 12337) ; / / ret urns "10" ( l i t t l e- endi an)
FlattenVar(anytype) Value
Return a string containing the byte representation of the specified variable.
st r i ngVal ue = Fl at t enVar ( mySt ruct) ;
UnflattenVar(string, anytype) Function
Convert a string containing the byte representation of the specified variable back intothe original variable type.
Unf l at t enVar ( st r i ngVal ue, mySt ruct ) ;
ByteArrayToStr(arr) Value
Convert the specified array to a string by appending a null terminator to the end of thearray elements. The array must be a one-dimensional array of byte.
mySt r = ByteArrayToSt r ( myArray);
ByteArrayToStrEx(arr, out str) Function
Convert the specified array to a string by appending a null terminator to the end of thearray elements. The array must be a one-dimensional array of byte.
ByteArrayToSt rEx(myArray, mySt r ) ;
3.1.4 Array Functions
StrToByteArray(str, out arr) Function
Convert the specified string to an array of byte by removing the null terminator at theend of the string. The output array variable must be a one-dimensional array of byte.
St rToByteArray( mySt r , myArray) ;
ArrayLen(array) Value
Return the length of the specified array.x = ArrayLen( myArray) ;
ArrayInit(array, value, count) Function
Initialize the array to contain count elements with each element equal to the valueprovided. To initialize a multi-dimensional array, the value should be an array of N-1dimensions, where N is the number of dimensions in the array being initialized.
-
5/26/2018 NXC_Guide
28/123
NXC Programmer's Guide
Page 23
ArrayI ni t ( myArray, 0, 10) ; / / 10 el ement s == zero
ArraySubset(out aout, asrc, idx, len) Function
Copy a subset of the source array starting at the specified index and containing thespecified number of elements into the destination array.
ArraySubset( myArray, sr cAr ray, 2, 5) ; copy 5 el ement s
ArrayBuild(out aout, src1 [, src2, , srcN]) Function
Build a new array from the specified source(s). The sources can be of any type. If asource is an array then all of its elements are added to the output array.
ArrayBui l d( myArray, sr c1, sr c2) ;
3.1.5 Numeric Functions
Random(n) ValueReturn an unsigned 16-bit random number between 0 and n (exclusive). N can be aconstant or a variable.
x = Random( 10) ; / / ret urn a val ue of 0. . 9
Random() Value
Return a signed 16-bit random number.
x = Random( ) ;
Sqrt(x) Value
Return the square root of the specified value.
x = Sqrt (x) ;
Sin(degrees) Value
Return the sine of the specified degrees value. The result is 100 times the sine value (-100..100).
x = Si n( theta) ;
Cos(degrees) Value
Return the cosine of the specified degrees value. The result is 100 times the cosinevalue (-100..100).
x = Cos(y) ;
-
5/26/2018 NXC_Guide
29/123
NXC Programmer's Guide
Page 24
Asin(value) Value
Return the inverse sine of the specified value (-100..100). The result is degrees (-90..90).
deg = Asi n( 80) ;
Acos(value) Value
Return the inverse cosine of the specified value (-100..100). The result is degrees(0..180).
deg = Acos( 0) ;
bcd2dec(bcdValue) Value
Return the decimal equivalent of the binary coded decimal value provided.
dec = bcd2dec(0x3a);
3.1.6 Low-level System FunctionsThere are several standard structures that are defined by the NXC API for use with callsto low-level system functions defined within the NXT firmware. These structures are themeans for passing values into the system functions and for returning values from thesystem functions. In order to call a system function you will need to declare a variable ofthe required system function structure type, set the structure members as needed by thesystem function, call the function, and then read the results, if desired.
Many of these system functions are wrapped into higher level NXC API functions so thatthe details are hidden from view. Using these low-level API calls you can improve thespeed of your programs a little.
If you install the NBC/NXC enhanced standard NXT firmware on your NXT all thescreen drawing system function also supports clearing pixels in addition to setting them.To switch from setting pixels to clearing pixels just specify theDRAW_OPT_CLEAR_PI XELSvalue (0x0004) in the Options member of the structures.This value can be ORed together with the DRAW_OPT_CLEAR_WHOLE_SCREENvalue(0x0001) if desired. Also, some of the system functions and their associated structures areonly supported by the NBC/NXC enhanced standard NXT firmware. These functions aremarked with (+)to indicate this additional requirement.
The first two structures define types are used within several other structures required bythe screen drawing system functions.
st ruct Locat i onType { i nt X; i nt Y;};
st ruct Si zeType { i nt Wi dt h; i nt Hei ght ;};
-
5/26/2018 NXC_Guide
30/123
NXC Programmer's Guide
Page 25
SysDrawText(DrawTextType & args) Function
This function lets you draw text on the NXT LCD given the parameters you pass in viathe DrawTextType structure. The structure type declaration is shown below.
st ruct DrawTextType { char Resul t ; Locat i onType Locati on; st r i ng Text ; unsi gned l ong Opt i ons;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
DrawTextType dtArgs;dtArgs. Locat i on. X = 0;dtArgs. Locat i on. Y = LCD_LI NE1;dtArgs. Text = "Pl ease Work";dtArgs. Opt i ons = 0x01; / / cl ear bef ore drawi ngSysDrawText( dtArgs) ;
SysDrawPoint(DrawPointType & args) Function
This function lets you draw a pixel on the NXT LCD given the parameters you pass invia the DrawPointType structure. The structure type declaration is shown below.
st ruct DrawPoi ntType { char Resul t ; Locat i onType Locati on; unsi gned l ong Opt i ons;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
DrawPoi ntType dpArgs;dpArgs. Locat i on. X = 20;dpArgs. Locat i on. Y = 20;dpArgs. Opt i ons = 0x04; / / cl ear t hi s pi xelSysDrawPoi nt ( dpArgs) ;
SysDrawLine(DrawLineType & args) Function
This function lets you draw a line on the NXT LCD given the parameters you pass in via
the DrawLineType structure. The structure type declaration is shown below.st ruct DrawLi neType { char Resul t ; Locat i onType Star tLoc; Locat i onType EndLoc; unsi gned l ong Opt i ons;};
-
5/26/2018 NXC_Guide
31/123
NXC Programmer's Guide
Page 26
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
DrawLi neType dl Args;dl Args. Star t Loc. X = 20;dl Args. Star t Loc. Y = 20;
dl Args. EndLoc. X = 60;dl Args. EndLoc. Y = 60;dl Args. Opt i ons = 0x01; / / cl ear bef ore drawi ngSysDrawLi ne(dl Args) ;
SysDrawCircle(DrawCircleType & args) Function
This function lets you draw a circle on the NXT LCD given the parameters you pass invia the DrawCircleType structure. The structure type declaration is shown below.
st ruct DrawCi rcl eType { char Resul t ; Locat i onType Center;
byte Si ze; unsi gned l ong Opt i ons;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
DrawCi rcl eType dcArgs;dcArgs. Center . X = 20;dcArgs. Center . Y = 20;dcArgs. Si ze = 10; / / r adi usdcArgs. Opt i ons = 0x01; / / cl ear bef ore drawi ngSysDrawCi rcl e(dcArgs) ;
SysDrawRect(DrawRectType & args) Function
This function lets you draw a rectangle on the NXT LCD given the parameters you passin via the DrawRectType structure. The structure type declaration is shown below.
st ruct DrawRectType { char Resul t ; Locat i onType Locati on; Si zeType Si ze; unsi gned l ong Opt i ons;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
DrawRect Type drArgs;drArgs. Locat i on. X = 20;drArgs. Locat i on. Y = 20;drArgs. Si ze. Wi dth = 20;drArgs. Si ze. Hei ght = 10;drArgs. Opt i ons = 0x00; / / do not cl ear bef ore drawi ngSysDrawRect( drArgs) ;
-
5/26/2018 NXC_Guide
32/123
NXC Programmer's Guide
Page 27
SysDrawGraphic(DrawGraphicType & args) Function
This function lets you draw a graphic image (RIC file) on the NXT LCD given theparameters you pass in via the DrawGraphicType structure. The structure typedeclaration is shown below.
st ruct DrawGraphi cType { char Resul t ; Locat i onType Locati on; st r i ng Fi l ename; i nt Vari abl es[] ; unsi gned l ong Opt i ons;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
DrawGraphi cType dgArgs;dgArgs. Locat i on. X = 20;
dgArgs. Locat i on. Y = 20;dgArgs. Fi l ename = "i mage. r i c";Ar rayI ni t ( dgArgs. Var i abl es, 0, 10) ; / / 10 zerosdgArgs. Var i abl es[ 0] = 12;dgArgs. Var i abl es[1] = 14; / / et c. . .dgArgs. Opt i ons = 0x00; / / do not cl ear bef ore drawi ngSysDrawGraphi c( dgArgs) ;
SysSetScreenMode(SetScreenModeType & args) Function
This function lets you set the screen mode of the NXT LCD given the parameters youpass in via the SetScreenModeType structure. The standard NXT firmware only supportssetting the ScreenMode to SCREEN_MODE_RESTORE, which has a value of 0x00. If youinstall the NBC/NXC enhanced standard NXT firmware this system function alsosupports setting the ScreenMode to SCREEN_MODE_CLEAR, which has a value of 0x01.The structure type declaration is shown below.
st ruct Set ScreenModeType { char Resul t ; unsi gned l ong ScreenMode;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
SetScr eenModeType ssmArgs;
ssmArgs. ScreenMode = 0x00; / / restore defaul t NXT screenSysSetScreenMode(ssmArgs) ;
SysSoundPlayFile(SoundPlayFileType & args) Function
This function lets you play a sound file given the parameters you pass in via theSoundPlayFileType structure. The sound file can either be an RSO file containing PCM
-
5/26/2018 NXC_Guide
33/123
NXC Programmer's Guide
Page 28
or compressed ADPCM samples or it can be an NXT melody (RMD) file containingfrequency and duration values. The structure type declaration is shown below.
st ruct SoundPl ayFi l eType { char Resul t ; st r i ng Fi l ename;
bool Loop; byte SoundLevel ;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
SoundPl ayFi l eType spf Args;spf Args. Fi l ename = "hel l o. rso";spf Args. Loop = f al se;spf Args. SoundLevel = 3;SysSoundPl ayFi l e( spf Args) ;
SysSoundPlayTone(SoundPlayToneType & args) FunctionThis function lets you play a tone given the parameters you pass in via theSoundPlayToneType structure. The structure type declaration is shown below.
st ruct SoundPl ayToneType { char Resul t ; unsi gned i nt Frequency; unsi gned i nt Durat i on; bool Loop; byte SoundLevel ;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
SoundPl ayToneType sptArgs;sptArgs. Frequency = 440;sptArgs. Durat i on = 1000; / / 1 secondsptArgs. Loop = f al se;sptArgs. SoundLevel = 3;SysSoundPl ayTone(sptArgs) ;
SysSoundGetState(SoundGetStateType & args) Function
This function lets you retrieve information about the sound module state via the
SoundGetStateType structure. Constants for sound state are SOUND_STATE_I DLE,SOUND_STATE_FI LE, SOUND_STATE_TONE, and SOUND_STATE_STOP. Constants forsound flags are SOUND_FLAGS_I DLE, SOUND_FLAGS_UPDATE, andSOUND_FLAGS_RUNNI NG. The structure type declaration is shown below.
st ruct SoundGetStateType { byte State; byte Fl ags;};
-
5/26/2018 NXC_Guide
34/123
NXC Programmer's Guide
Page 29
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
SoundGetStateType sgsArgs;SysSoundGetState(sgsArgs) ;i f ( sgsArgs. State == SOUND_STATE_I DLE) {/ * do st uf f */ }
SysSoundSetState(SoundSetStateType & args) Function
This function lets you set sound module state settings via the SoundSetStateTypestructure. Constants for sound state are SOUND_STATE_I DLE, SOUND_STATE_FI LE,SOUND_STATE_TONE, and SOUND_STATE_STOP. Constants for sound flags areSOUND_FLAGS_I DLE, SOUND_FLAGS_UPDATE, and SOUND_FLAGS_RUNNI NG. Thestructure type declaration is shown below.
st ruct SoundSetStateType { byte Resul t ; byte State; byte Fl ags;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
SoundSetSt ateType sssArgs;sssArgs. State = SOUND_STATE_STOP;SysSoundSetState(sssArgs) ;
SysReadButton(ReadButtonType & args) Function
This function lets you read button state information via the ReadButtonType structure.The structure type declaration is shown below.
st ruct ReadBut tonType { char Resul t ; byte I ndex; bool Pressed; byte Count; bool Reset ; / / reset count af t er r eadi ng?};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
ReadButtonType rbArgs;
rbArgs. I ndex = BTNRI GHT;SysReadBut ton( rbArgs) ;i f ( rbArgs. Pressed) {/ * do somethi ng */ }
SysRandomNumber(RandomNumberType & args) Function
This function lets you obtain a random number via the RandomNumberType structure.The structure type declaration is shown below.
-
5/26/2018 NXC_Guide
35/123
NXC Programmer's Guide
Page 30
st ruct RandomNumberType { i nt Resul t ;};
Declare a variable of this type and then call the function, passing in your variable of thisstructure type.
RandomNumber Type r nArgs;SysRandomNumber( rnArgs) ;i nt myRandomVal ue = rnArgs. Resul t ;
SysGetStartTick(GetStartTickType & args) Function
This function lets you obtain the tick value at the time your program began executing viathe GetStartTickType structure. The structure type declaration is shown below.
st ruct Get Star t Ti ckType { unsi gned l ong Resul t ;};
Declare a variable of this type and then call the function, passing in your variable of thisstructure type.
GetStar t Ti ckType gstArgs;SysGetStar t Ti ck( gstArgs) ;unsi gned l ong myStart = gst Args. Resul t ;
SysKeepAlive(KeepAliveType & args) Function
This function lets you reset the sleep timer via the KeepAliveType structure. Thestructure type declaration is shown below.
st ruct KeepAl i veType {
unsi gned l ong Resul t ;};
Declare a variable of this type and then call the function, passing in your variable of thisstructure type.
KeepAl i veType kaArgs;SysKeepAl i ve( kaArgs) ; / / reset sl eep t i mer
SysFileOpenWrite(FileOpenType & args) Function
This function lets you create a file that you can write to using the values specified via theFileOpenType structure. The structure type declaration is shown below. Use the
FileHandle return value for subsequent file write operations. The desired maximum filecapacity in bytes is specified via the Length member.
st ruct Fi l eOpenType { unsi gned i nt Resul t ; byte Fi l eHandl e; st r i ng Fi l ename; unsi gned l ong Length;};
-
5/26/2018 NXC_Guide
36/123
NXC Programmer's Guide
Page 31
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
Fi l eOpenType f oArgs;f oArgs. Fi l ename = "myf i l e. t xt ";f oArgs. Length = 256; / / create wi t h capaci t y for 256 bytes
SysFi l eOpenWr i t e( f oArgs) ; / / creat e t he f i l ei f ( f oArgs. Resul t == NO_ERR) { / / wr i te t o t he f i l e usi ng Fi l eHandl e}
SysFileOpenAppend(FileOpenType & args) Function
This function lets you open an existing file that you can write to using the valuesspecified via the FileOpenType structure. The structure type declaration is shown below.Use the FileHandle return value for subsequent file write operations. The availablelength remaining in the file is returned via the Length member.
st ruct Fi l eOpenType {
unsi gned i nt Resul t ; byte Fi l eHandl e; st r i ng Fi l ename; unsi gned l ong Length;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
Fi l eOpenType f oArgs;f oArgs. Fi l ename = "myf i l e. t xt ";SysFi l eOpenAppend( f oArgs) ; / / open the f i l ei f ( f oArgs. Resul t == NO_ERR) {
/ / wr i te t o t he f i l e usi ng Fi l eHandl e / / up to t he remai ni ng avai l abl e l ength i n Length}
SysFileOpenRead(FileOpenType & args) Function
This function lets you open an existing file for reading using the values specified via theFileOpenType structure. The structure type declaration is shown below. Use theFileHandle return value for subsequent file read operations. The number of bytes thatcan be read from the file is returned via the Length member.
st ruct Fi l eOpenType {
unsi gned i nt Resul t ; byte Fi l eHandl e; st r i ng Fi l ename; unsi gned l ong Length;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
-
5/26/2018 NXC_Guide
37/123
NXC Programmer's Guide
Page 32
Fi l eOpenType f oArgs;f oArgs. Fi l ename = "myf i l e. t xt ";SysFi l eOpenRead( f oArgs) ; / / open t he f i l e f or readi ngi f ( f oArgs. Resul t == NO_ERR) { / / read data f romt he f i l e usi ng Fi l eHandl e}
SysFileRead(FileReadWriteType & args) Function
This function lets you read from a file using the values specified via theFileReadWriteType structure. The structure type declaration is shown below.
st ruct Fi l eReadWr i t eType { unsi gned i nt Resul t ; byte Fi l eHandl e; st r i ng Buf f er ; unsi gned l ong Length;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
Fi l eReadWr i t eType f rArgs;f rArgs. Fi l eHandl e = f oArgs. Fi l eHandl e;f rArgs. Length = 12; / / number of bytes t o readSysFi l eRead( f rArgs) ;i f ( f rArgs. Resul t == NO_ERR) { TextOut ( 0, LCD_LI NE1, f rArgs. Buf f er ) ; / / show how many bytes were actual l y read NumOut (0, LCD_LI NE2, f rArgs. Length) ;}
SysFileWrite(FileReadWriteType & args) Function
This function lets you write to a file using the values specified via theFileReadWriteType structure. The structure type declaration is shown below.
st ruct Fi l eReadWr i t eType { unsi gned i nt Resul t ; byte Fi l eHandl e; st r i ng Buf f er ; unsi gned l ong Length;};
Declare a variable of this type, set its members, and then call the function, passing in
your variable of this structure type.Fi l eReadWr i t eType f wArgs;f wArgs. Fi l eHandl e = f oArgs. Fi l eHandl e;f wArgs. Buf f er = "data t o wr i te";SysFi l eWri t e( f wArgs) ;i f ( f wArgs. Resul t == NO_ERR) { / / di spl ay number of bytes wr i t t en
-
5/26/2018 NXC_Guide
38/123
NXC Programmer's Guide
Page 33
NumOut(0, LCD_LI NE1, f wArgs. Length) ;}
SysFileClose(FileCloseType & args) Function
This function lets you close a file using the values specified via the FileCloseType
structure. The structure type declaration is shown below.st ruct Fi l eCl oseType { unsi gned i nt Resul t ; byte Fi l eHandl e;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
Fi l eCl oseType f cArgs;f cArgs. Fi l eHandl e = f oArgs. Fi l eHandl e;SysFi l eCl ose( f cArgs) ;
SysFileResolveHandle(FileResolveHandleType & args) Function
This function lets you resolve the handle of a file using the values specified via theFileResolveHandleType structure. The structure type declaration is shown below.
st ruct Fi l eResol veHandl eType { unsi gned i nt Resul t ; byte Fi l eHandl e; bool Wr i t eHandl e; st r i ng Fi l ename;};
Declare a variable of this type, set its members, and then call the function, passing in
your variable of this structure type.
Fi l eResol veHandl eType f rhArgs;f rhArgs. Fi l ename = "myf i l e. t xt ";SysFi l eResol veHandl e( f rhArgs) ;i f ( f rhArgs. Resul t == LDR_SUCCESS) { / / use t he Fi l eHandl e as needed i f ( f rhArgs. Wr i t eHandl e) { / / f i l e i s open f or wri t i ng } el se { / / f i l e i s open f or readi ng
}}
SysFileRename(FileRenameType & args) Function
This function lets you rename a file using the values specified via the FileRenameTypestructure. The structure type declaration is shown below.
st ruct Fi l eRenameType { unsi gned i nt Resul t ;
-
5/26/2018 NXC_Guide
39/123
NXC Programmer's Guide
Page 34
st r i ng Ol dFi l ename; st r i ng NewFi l ename;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
Fi l eRenameType f rArgs;f rArgs. Ol dFi l ename = "myf i l e. t xt ";f rArgs. NewFi l ename = "myf i l e2. t xt ";SysFi l eRename(f rArgs) ;i f ( f rArgs. Resul t == LDR_SUCCESS) { / * do somethi ng */ }
SysFileDelete(FileDeleteType & args) Function
This function lets you delete a file using the values specified via the FileDeleteTypestructure. The structure type declaration is shown below.
st ruct Fi l eDel eteType { unsi gned i nt Resul t ; st r i ng Fi l ename;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
Fi l eDel eteType f dArgs;f dArgs. Fi l ename = "myf i l e. t xt ";SysFi l eDel ete( f dArgs); / / del ete t he f i l e
SysCommLSWrite(CommLSWriteType & args) Function
This function lets you write to an I2C (Lowspeed) sensor using the values specified via
the CommLSWriteType structure. The structure type declaration is shown below.
st ruct CommLSWr i t eType { char Resul t ; byte Por t ; byte Buf f er [ ] ; byte ReturnLen;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
CommLSWr i t eType args;
args. Por t = S1;args. Buf f er = myBuf ;args. ReturnLen = 8;SysCommLSWr i t e(args) ;/ / check Resul t f or er ror status
-
5/26/2018 NXC_Guide
40/123
NXC Programmer's Guide
Page 35
SysCommLSCheckStatus(CommLSCheckStatusType & args) Function
This function lets you check the status of an I2C (Lowspeed) sensor transaction using thevalues specified via the CommLSCheckStatusType structure. The structure typedeclaration is shown below.
st ruct CommLSCheckStatusType { char Resul t ; byte Por t ; byte BytesReady;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
CommLSCheckStatusType ar gs;args. Por t = S1;SysCommLSCheckStatus( args) ;/ / i s the status (Resul t ) I DLE?
i f ( args. Resul t == LOWSPEED_I DLE) { / * proceed */ }
SysCommLSRead(CommLSReadType & args) Function
This function lets you read from an I2C (Lowspeed) sensor using the values specified viathe CommLSReadType structure. The structure type declaration is shown below.
st ruct CommLSReadType { char Resul t ; byte Por t ; byte Buf f er [ ] ; byte Buf f erLen;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
CommLSReadType ar gs;args. Por t = S1;args. Buf f er = myBuf ;args. Buf f erLen = 8;SysCommLSRead(args) ;/ / check Resul t f or er ror st atus & use Buf f er content s
SysMessageWrite(MessageWriteType & args) Function
This function lets you write a message to a queue (aka mailbox) using the valuesspecified via the MessageWriteType structure. The structure type declaration is shownbelow.
st ruct MessageWr i t eType { char Resul t ; byte QueueI D; st r i ng Message;};
-
5/26/2018 NXC_Guide
41/123
NXC Programmer's Guide
Page 36
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
MessageWri t eType args;args. QueueI D = MAI LBOX1; / / 0args. Message = "t est i ng";
SysMessageWr i t e(args) ;/ / check Resul t f or er ror status
SysMessageRead(MessageReadType & args) Function
This function lets you read a message from a queue (aka mailbox) using the valuesspecified via the MessageReadType structure. The structure type declaration is shownbelow.
st ruct MessageReadType { char Resul t ; byte QueueI D; bool Remove;
st r i ng Message;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
MessageReadType args;args. QueueI D = MAI LBOX1; / / 0args. Remove = t rue;SysMessageRead( args) ;i f ( args. Resul t == NO_ERR) { TextOut ( 0, LCD_LI NE1, args. Message);}
SysCommBTWrite(CommBTWriteType & args) Function
This function lets you write to a Bluetooth connection using the values specified via theCommBTWriteType structure. The structure type declaration is shown below.
st ruct CommBTWr i t eType { char Resul t ; byte Connect i on; byte Buf f er [ ] ;};
Declare a variable of this type, set its members, and then call the function, passing in
your variable of this structure type.CommBTWr i t eType args;args. Connect i on = 1;args. Buf f er = myData;SysCommBTWr i t e(args) ;
-
5/26/2018 NXC_Guide
42/123
NXC Programmer's Guide
Page 37
SysCommBTCheckStatus(CommBTCheckStatusType & args) Function
This function lets you check the status of a Bluetooth connection using the valuesspecified via the CommBTCheckStatusType structure. The structure type declaration isshown below. Possible values for Result include ERR_I NVALI D_PORT,STAT_COMM_PENDI NG, ERR_COMM_CHAN_NOT_READY, and LDR_SUCCESS(0).
st ruct CommBTCheckStatusType { char Resul t ; byte Connect i on; byte Buf f er [ ] ;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
CommBTCheckSt at usType args;args. Connect i on = 1;SysCommBTCheckStatus( args) ;
i f ( args. Resul t == LDR_SUCCESS) { / * do somethi ng */ }
SysIOMapRead(IOMapReadType & args) Function
This function lets you read data from a firmware module's IOMap using the valuesspecified via the IOMapReadType structure. The structure type declaration is shownbelow.
st ruct I OMapReadType { char Resul t ; st r i ng Modul eName; unsi gned i nt Of f set ; unsi gned i nt Count ;
byte Buf f er [ ] ;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
I OMapReadType args;ar gs. Modul eName = CommandModul eName;args. Of f set = CommandOf f setTi ck;args. Count = 4; / / thi s val ue happens t o be 4 bytes l ongSysI OMapRead( args) ;i f ( args. Resul t == NO_ERR) { / * do somethi ng wi th data */ }
SysIOMapWrite(IOMapWriteType & args) Function
This function lets you write data to a firmware module's IOMap using the valuesspecified via the IOMapWriteType structure. The structure type declaration is shownbelow.
st ruct I OMapWr i t eType { char Resul t ; st r i ng Modul eName;
-
5/26/2018 NXC_Guide
43/123
NXC Programmer's Guide
Page 38
unsi gned i nt Of f set ; byte Buf f er [ ] ;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
I OMapWr i teType args;args. Modul eName = SoundModul eName;args. Of f set = SoundOf f setSampl eRate;args. Buf f er = theData;SysI OMapWr i t e(args) ;
SysIOMapReadByID(IOMapReadByIDType & args) Function (+)
This function lets you read data from a firmware module's IOMap using the valuesspecified via the IOMapReadByIDType structure. The structure type declaration isshown below. This function can be as much as three times faster than usingSysIOMapRead since it does not have to do a string lookup using the ModuleName.
st ruct I OMapReadByI DType { char Resul t ; unsi gned l ong Modul eI D; unsi gned i nt Of f set ; unsi gned i nt Count ; byte Buf f er [ ] ;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
I OMapReadByI DType args;
args. Modul eI D = CommandModul eI D;args. Of f set = CommandOf f setTi ck;args. Count = 4; / / thi s val ue happens t o be 4 bytes l ongSysI OMapReadByI D( args) ;i f ( args. Resul t == NO_ERR) { / * do somethi ng wi th data */ }
SysIOMapWriteByID(IOMapWriteByIDType & args) Function (+)
This function lets you write data to a firmware module's IOMap using the valuesspecified via the IOMapWriteByIDType structure. The structure type declaration isshown below. This function can be as much as three times faster than usingSysIOMapWrite since it does not have to do a string lookup using the ModuleName.
st ruct I OMapWr i t eByI DType { char Resul t ; unsi gned l ong Modul eI D; unsi gned i nt Of f set ; byte Buf f er [ ] ;};
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
-
5/26/2018 NXC_Guide
44/123
NXC Programmer's Guide
Page 39
I OMapWr i teByI DType args;args. Modul eI D = SoundModul eI D;args. Of f set = SoundOf f setSampl eRate;args. Buf f er = theData;SysI OMapWr i t eByI D( args) ;
SysDisplayExecuteFunction(DisplayExecuteFunctionType & args)Function (+)
This function lets you directly execute the Display module's primary drawing functionusing the values specified via the DisplayExecuteFunctionType structure. The structuretype declaration is shown below. The values for these fields are documented in the tablebelow. If a field member is shown as 'x' it is ignored by the specified display command.
st ruct Di spl ayExecuteFunct i onType { byte Status; byte Cmd; bool On; byte X1; byte Y1; byte X2; byte Y2;};
Cmd Meaning Expected parameters
DISPLAY_ERASE_ALL erase entire screen ()
DISPLAY_PIXEL set pixel (on/off) (true/false,X1,Y1,x,x)
DISPLAY_HORIZONTAL_LINE draw horizontal line (true/false,X1,Y1,X2,x)
DISPLAY_VERTICAL_LINE draw vertical line (true/false,X1,Y1,x,Y2)
DISPLAY_CHAR draw char (actual font) (true/false,X1,Y1,Char,x)DISPLAY_ERASE_LINE erase a single line (x,LINE,x,x,x)
DISPLAY_FILL_REGION fill screen region (true/false,X1,Y1,X2,Y2)
DISPLAY_FILLED_FRAME draw a frame (on / off) (true/false,X1,Y1,X2,Y2)
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
Di spl ayExecuteFunct i onType args;args. Cmd = DI SPLAY_ERASE_ALL;SysDi spl ayExecuteFunct i on( args) ;
SysCommExecuteFunction(CommExecuteFunctionType & args)Function (+)
This function lets you directly execute the Comm module's primary function using thevalues specified via the CommExecuteFunctionType structure. The structure typedeclaration is shown below. The values for these fields are documented in the tablebelow. If a field member is shown as 'x' it is ignored by the specified display command.
-
5/26/2018 NXC_Guide
45/123
NXC Programmer's Guide
Page 40
st ruct CommExecuteFunct i onType { unsi gned i nt Resul t ; byte Cmd; byte Param1; byte Param2; byte Param3;
st r i ng Name; unsi gned i nt RetVal ;};
Cmd Meaning (Param1,Param2,Param3,Name)
INTF_SENDFILE Send a file over aBluetooth connection
(Connection,x,x,Filename)
INTF_SEARCH Search for Bluetoothdevices
(x,x,x,x)
INTF_STOPSEARCH Stop searching for
Bluetooth devices
(x,x,x,x)
INTF_CONNECT Connect to a Bluetoothdevice
(DeviceIndex,Connection,x,x)
INTF_DISCONNECT Disconnect a Bluetoothdevice
(Connection,x,x,x)
INTF_DISCONNECTALL Disconnect allBluetooth devices
(x,x,x,x)
INTF_REMOVEDEVICE Remove device fromMy Contacts
(DeviceIndex,x,x,x)
INTF_VISIBILITY Set Bluetooth visibility (true/false,x,x,x)INTF_SETCMDMODE Set command mode (x,x,x,x)
INTF_OPENSTREAM Open a stream (x,Connection,x,x)
INTF_SENDDATA Send data (Length, Connection, WaitForIt,Buffer)
INTF_FACTORYRESET Bluetooth factory reset (x,x,x,x)
INTF_BTON Turn Bluetooth on (x,x,x,x)
INTF_BTOFF Turn Bluetooth off (x,x,x,x)
INTF_SETBTNAME Set Bluetooth name (x,x,x,x)
INTF_EXTREAD Handle external? read (x,x,x,x)
INTF_PINREQ Handle Blueooth PINrequest
(x,x,x,x)
INTF_CONNECTREQ Handle Bluetoothconnect request
(x,x,x,x)
-
5/26/2018 NXC_Guide
46/123
NXC Programmer's Guide
Page 41
Declare a variable of this type, set its members, and then call the function, passing inyour variable of this structure type.
CommExecuteFunct i onType args;args. Cmd = I NTF_BTOFF;SysCommExecuteFunct i on(args) ;
SysLoaderExecuteFunction(LoaderExecuteFunctionType & args)Function (+)
This function lets you directly execute the Loader