IC Programmers Manual for the Xport Botball Controller
Programmers Manual Index
  1. Introduction
  2. Using IC
  3. IC Interface
  4. The main() Function
  5. IC versus Standard C
  6. Data Objects
  7. Statements and Expressions
  8. Assignment Operators and Expressions
  9. Increment and Decrement Operators
  10. Data Access Operators
  11. Precedence and Order of Evaluation
  12. Control Flow
  13. Statements and Blocks
  14. LCD Screen Printing
  15. Preprocessor
  16. The IC Library File
  17. Sensors
  18. Alphabetic List of Functions
  19. IC Vision API for the XBC
  20. Simulator Instructions

Interactive C (IC for short) is a C language consisting of a compiler (with interactive command-line compilation and debugging) and a run-time machine language module. IC implements a subset of C including control structures (for, while, if, else), local and global variables, arrays, pointers, structures, 16-bit and 32-bit integers, and 32-bit floating point numbers.

IC works by compiling into pseudo-code for a custom stack machine, rather than compiling directly into native code for a particular processor. This pseudo-code (or p-code) is then interpreted by the run-time machine language program. This unusual approach to compiler design allows IC to offer the following design tradeoffs:

Since IC's ultimate performance is limited by the fact that its output p-code is interpreted, these advantages are taken at the expense of raw execution speed.
IC 5 was written by Kyle Machulis/KISS Institute for Practical Robotics. Portions of the code and the libraries are based on the public distribution of IC 4.x by Randy Sargent with assistance from Mark Sherman, and IC 2.8, written by Randy Sargent, Anne Wright and Fred Martin.

Using IC   Index

When IC is running and has a connection to a compatible processor board such as the Handy Board or RCX, C expressions, function calls, and IC commands may be typed in the command entry portion of the interaction window.

For example, to evaluate the arithmetic expression 1 + 2, type in the following:
   1 + 2;
When this expression is entered from the interaction window, it is compiled by the console computer and then downloaded to the attached system for evaluation. The connected board then evaluates the compiled form and returns the result, which is printed on the display section of console interaction window.

To evaluate a series of expressions, create a C block by beginning with an open curly brace { and ending with a close curly brace }. The following example creates a local variable i and prints 10 (the sum of i + 7) to the board's LCD screen:
   {int i=3; printf("%d", i+7);}

IC Interface   Index

Both new (unsaved) and saved files can be opened for editing in IC. A row of tabs lists the files that have been opened. Clicking a file's tab activates it for editing. The first tab for the interface is always the interaction window.

The File button has standard entries for New, Open, Close, Save, Save As, Print, and Exit. Under File - Save As, if no file name extension is supplied, IC automatically saves with the ".ic" extension.

To download the active file, simply click the download button. The active file will also be saved, unless it is new, in which case the user is prompted for a "save as" file name. Remark: a preprocessor command #use has been added to IC to specify any other saved files (personal libraries) that need to be downloaded along with the active file [Note: #use is quite different from the #include prepreocessor command of standard C environments. #include is not implemented for reasons given later in the section describing the IC-preprocessor.]

If a downloaded program does not do what is intended, it may corrupt the p-code interpreter, particularly if pointers are being employed. The interface provides an option under the Settings button for downloading the firmware to reinitialize the board.

When there is a connection to a board and the downloaded programs include "main", then "main" can be executed using the Run Main button. The Stop button will halt execution of the attached system.

Under the Tools button, among other options, are ones for listing downloaded files, global variables, and functions (including library functions).

The interface provides additional capabilities for program entry/edit, minor adjustment to the display, and for setting up the serial interface to a board. In particular, the Check tool will perform a syntax check of the C program currently in the window. If there is an error, the approximate line number where the error is located is reported (the error is on the line or a nearby prior line). The edit button provides a Go to line option.

C programs are automatically formatted and indented. Keywords, library functions, comments, and text strings are high-lighted with color unless this feature is turned off.

IC does parenthesis-balance-highlighting when the cursor is placed to the right of any right parenthesis, bracket, or brace.

The main() Function   Index

After functions have been downloaded to a board, they can be invoked from IC so long as the board is connected. If one of the functions is named main(), it can be run directly from the interface as noted earlier, and otherwise will be run automatically when the board is reset.

Note: to reset the Handy Board without running the main() function (for instance, when hooking the board back to the computer), hold down the boarentry.d's Start button while activating the board. The board will then reset without running main().

IC versus Standard C   Index

The IC programming language is based loosely on ANSI C. However, there are major differences.

Many of these differences arise from the desire to have IC be "safer" than standard C. For instance, in IC, array bounds are checked at run time; for this reason, arrays cannot be converted to pointers in IC. Also, in IC, pointer arithmetic is not allowed.

Other differences are due to the desire that the IC runtime be small and efficient. For instance, the IC printf function does not understand many of the more exotic formatting options specified by ANSI C.

Yet other differences are due to the desire that IC be simpler than standard C. This is the reason for the global scope of all declarations.

In the rest of this document, when we refer to "C", the statement applies to both IC and standard C. When we wish to specify one or the other, we will refer to either "IC" or "standard C". When no such qualifiers are present, you should assume that we are talking about IC.

A Quick C Tutorial   Index

Most C programs consist of function definitions and data structures. Here is a simple C program that defines a single function, called main.

/* Simple example
IC Programmer's Manual
void main()
printf("Hello, world!\n"); // Something simple }
The expression
/* <text> */
forms a multi-line or bracketed comment. In contrast, text that starts with "//" forms a single line comment, which continues only to the end of the line. Comments are ignored by IC when the program is compiled.

All functions must have a return type. Since main does not return a value, it uses void, the null type, as its return type. Other types include integers (int) and floating point numbers (float). This function declaration information must precede each function definition.

Immediately following the function declaration is the function's name (in this case, main). Next, in parentheses, are any arguments (or inputs) to the function. main has none, but an empty set of parentheses is still required.

After the function arguments is an open curly-brace {. This signifies the start of the actual function code. Curly-braces signify program blocks, or chunks of code.

Next comes a series of C statements. Statements demand that some action be taken. Our demonstration program has a single statement, a printf (formatted print). This will print the message "Hello, world!" to the LCD display. The \n indicates end-of-line. The printf statement ends with a semicolon (;). All C statements must be ended by a semicolon. Beginning C programmers commonly make the error of omitting the semicolon that is required to end each statement.

The main function is ended by the close curly-brace }.

Let's look at an another example to learn some more features of C. The following code defines the function square, which returns the mathematical square of a number.

int square(int n)
return(n * n);
The function is declared as type int, which means that it will return an integer value.

Next comes the function named square, followed by its argument list in parentheses. square has one argument, n, which is an integer. Notice how declaring the type of the argument is done similarly to declaring the type of the function.

When a function has arguments declared, those argument variables are valid within the "scope" of the function (i.e., they only have meaning within the function's own code). Other functions may use the same variable names independently.

The code for square is contained within the set of curly braces. In fact, it consists of a single statement: the return statement. The return statement exits the function and returns the value of the C expression that follows it (in this case "n * n").

Except where grouped by parentheses, expressions are evaluated according to a set of precedence rules associated with the various operations within the expression. In this case, there is only one operation (multiplication), signified by the "*", so precedence is not an issue.

Let's look at an example of a function that performs a function call to the square program.

float hypotenuse(int a, int b)
float h;
h = sqrt((float)(square(a) + square(b)));
This code demonstrates several more features of C. First, notice that the floating point variable h is defined at the beginning of the hypotenuse function. In general, whenever a new program block (indicated by a set of curly braces) is begun, new local variables may be defined.

The value of h is set to the result of a call to the sqrt function. It turns out that sqrt is a built-in IC function that takes a floating point number as its argument.

We want to use the square function we defined earlier, which returns its result as an integer. But the sqrt function requires a floating point argument. We get around this type incompatibility by coercing the integer sum (square(a) + square(b)) into a float by preceding it with the desired type, in parentheses. Thus, the integer sum is made into a floating point number and passed along to sqrt.

The hypotenuse function finishes by returning the value of h.

This concludes the brief C tutorial.

Data Objects   Index

Variables and constants are the basic data objects in a C program. Declarations list the variables to be used, state what type they are, and may set their initial value.

Variables   Index

Variable names are case-sensitive. The underscore character is allowed and is often used to enhance the readability of long variable names. C keywords like if, while, etc. may not be used as variable names.

Functions and global variables may not have the same name. In addition, if a local variable is named the same as a function or a global variable, the local use takes precedence; ie., use of the function or global variable is prevented within the scope of the local variable.

Declaration   Index

In C, variables can be declared at the top level (outside of any curly braces) or at the start of each block (a functional unit of code surrounded by curly braces). In general, a variable declaration is of the form:
<type>   <variable-name>; or
<type>   <variable-name>=<initialization-data>;
In IC, <type> can be int, long, float, char, or struct <struct-name>, and determines the primary type of the variable declared. This form changes somewhat when dealing with pointer and array declarations, which are explained in a later section, but in general this is the way you declare variables.

Local and Global Scopes   Index

If a variable is declared within a function, or as an argument to a function, its binding is local, meaning that the variable has existence only within that function definition. If a variable is declared outside of a function, it is a global variable. It is defined for all functions, including functions which are defined in files other than the one in which the global variable was declared.

Variable Initialization   Index

Local and global variables can be initialized to a value when they are declared. If no initialization value is given, the variable is initialized to zero.

All global variable declarations must be initialized to constant values. Local variables may be initialized to the value of arbitrary expressions including any global variables, function calls, function arguments, or local variables which have already been initialized.

Here is a small example of how initialized declarations are used.

   int i=50;     /* declare i as global integer; initial value 50 */
   long j=100L;  /* declare j as global long; initial value 100 */
   int foo()
int x; /* declare x as local integer; initial value 0 */ long y=j; /* declare y as local integer; initial value j */ }
Local variables are initialized whenever the function containing them is executed. Global variables are initialized whenever a reset condition occurs. Reset conditions occur when:
  1. Code is downloaded;
  2. The main() procedure is run;
  3. System hardware reset occurs.

Persistent Global Variables   Index

A special persistent form of global variable, has been implemented for IC. A persistent global variable may be initialized just like any other global variable, but its value is only initialized when the code is downloaded and not on any other reset conditions. If no initialization information is included for a persistent variable, its value will be initialized to zero on download, but left unchanged on all other reset conditions.

To make a persistent global variable, prefix the type specifier with the keyword persistent. For example, the statement

   persistent int i=500;
creates a global integer called i with the initial value 500.

Persistent variables keep their state when the board is turned off and on, when main is run, and when system reset occurs. Persistent variables will lose their state when code is downloaded as a result of loading or unloading a file. However, it is possible to read the values of your persistent variables in IC if you are still running the same IC session from which the code was downloaded. In this manner you could read the final values of calibration persistent variables, for example, and modify the initial values given to those persistent variables appropriately.

Persistent variables were created with two applications in mind:
  • Calibration and configuration values that do not need to be re-calculated on every reset condition.
  • Robot learning algorithms that might occur over a period when the robot is turned on and off.

Constants   Index

Integer Constants   Index

Integers constants may be defined in decimal integer format (e.g., 4053 or -1), hexadecimal format using the "0x" prefix (e.g., 0x1fff), and a non-standard but useful binary format using the "0b" prefix (e.g., 0b1001001). Octal constants using the zero prefix are not supported.

Long Integer Constants   Index

Long integer constants are created by appending the suffix "l" or "L" (upper- or lower- case alphabetic L) to a decimal integer. For example, 0L is the long zero. Either the upper or lower-case "L" may be used, but upper-case is the convention for readability.

Floating Point Constants   Index

Floating point numbers may use exponential notation (e.g., "10e3" or "10E3") or may contain a decimal period. For example, the floating point zero can be given as "0.", "0.0", or "0E1", but not as just "0". Since the board has no floating point hardware, floating point operations are much slower than integer operations, and should be used sparingly.

Characters and String Constants   Index

Quoted characters return their ASCII value (e.g., 'x').

Character string constants are defined with quotation marks, e.g., "This is a character string.".

NULL   Index

The special constant NULL has the value of zero and can be assigned to and compared to pointer or array variables (which will be described in later sections). In general, you cannot convert other constants to be of a pointer type, so there are many times when NULL can be useful.

For example, in order to check if a pointer has been initialized you could compare its value to NULL and not try to access its contents if it was NULL. Also, if you had a defined a linked list type consisting of a value and a pointer to the next element, you could look for the end of the list by comparing the next pointer to NULL.

Data Types   Index

IC supports the following data types:

16-bit Integers   Index

16-bit integers are signified by the type indicator int. They are signed integers, and may be valued from -32,768 to +32,767 decimal.

32-bit Integers   Index

32-bit integers are signified by the type indicator long. They are signed integers, and may be valued from -2,147,483,648 to +2,147,483,647 decimal.

32-bit Floating Point Numbers   Index

Floating point numbers are signified by the type indicator float. They have approximately seven decimal digits of precision and are valued from about 10^-38 to 10^38.

8-bit Characters   Index

Characters are an 8-bit number signified by the type indicator char. A character's value typically represents a printable symbol using the standard ASCII character code, but this is not necessary; characters can be used to refer to arbitrary 8-bit numbers.

Pointers   Index IC pointers are 16-bit numbers which represent locations in memory. Values in memory can be manipulated by calculating, passing and dereferencing pointers representing the location where the information is stored.

Arrays   Index Arrays are used to store homogenous lists of data (meaning that all the elements of an array have the same type). Every array has a length which is determined at the time the array is declared. The data stored in the elements of an array can be set and retrieved in the same manner as for other variables.

Structures   Index

Structures are used to store non-homogenous but related sets of data. Elements of a structure are referenced by name instead of number and may be of any supported type.

Structures are useful for organizing related data into a coherent format, reducing the number of arguments passed to functions, increasing the effective number of values which can be returned by functions, and creating complex data representations such as directed graphs and linked lists.

Pointers   Index

The address where a value is stored in memory is known as the pointer to that value. It is often useful to deal with pointers to objects, but great care must be taken to insure that the pointers used at any point in your code really do point to valid objects in memory.

Attempts to refer to invalid memory locations could corrupt your memory. Most computing environments that you are probably used to return helpful messages like 'Segmentation Violation' or 'Bus Error' on attempts to access illegal memory. However, you won't have this safety net on the board you are connecting to. Invalid pointer dereferencing is very likely to go undetected, and will likely render invalid your data, your program, or even the pcode interpreter.

Pointer Safety   Index

In past versions of IC, you could not return pointers from functions or have arrays of pointers. In order to facilitate the use of structures, these features have been added to the current version. With this change, the number of opportunities to misuse pointers have increased. However, if you follow a few simple precautions you should do fine.

First, you should always check that the value of a pointer is not equal to NULL (a special zero pointer) before you try to access it. Variables which are declared to be pointers are initialized to NULL, so many uninitialized values could be caught this way.

Second, you should never use a pointer to a local variable in a manner which could cause it to be accessed after the function in which it was declared terminates. When a function terminates the space where its values were being stored is recycled. Therefore not only may dereferencing such pointers return incorrect values, but assigning to those addresses could lead to serious data corruption. A good way to prevent this is to never return the address of a local variable from the function which declares it and never store those pointers in an object which will live longer than the function itself (a global pointer, array, or struct). Global variables and variables local to main will not move once declared and their pointers can be considered to be secure.

The type checking done by IC will help prevent many mishaps, but it will not catch all errors, so be careful.

Pointer Declaration and Use   Index

A variable which is a pointer to an object of a given type is declared in the same manner as a regular object of that type, but with an extra * in front of the variable name.

The value stored at the location the pointer refers to is accessed by using the * operator before the expression which calculates the pointer. This process is known as dereferencing.

The address of a variable is calculated by using the & operator before that variable, array element, or structure element reference.

There are two main differences between how you would use a variable of a given type and a variable declared as a pointer to that type.

For the following explanation, consider X and Xptr as defined as follows:

   long X; long *Xptr;
So, for example, consider what would happen if the first two statements after X and Xptr were declared were the following:
   X=50L; *Xptr=50L;
The first statement is valid: it sets the value of X to 50L. The second statement would be valid if Xptr had been properly initialized, but in this case it has not. Therefore, this statement would corrupt memory.

Here is a sequence of commands you could try which illustrate how pointers and the * and & operators are used. It also shows that once a pointer has been set to point at a place in memory, references to it actually share the same memory as the object it points to:

   X=50L;               /* set the memory allocated for X to 50 */
   Xptr=&X;             /* set Xptr to point to memory address of X */
   printf("%d ",*Xptr); /* dereference Xptr; value at address is 50 */
   X=100L;              /* set X to the value 100 */
   printf("%d ",*Xptr); /* dereference again; value is now 100 */
   *Xptr=200L;          /* set value at address given by Xptr to 200 */
   printf("%d\n",X);    /* check that the value of X changed to 200 */

Passing Pointers as Arguments   Index

Pointers can be passed to functions and functions can change the values of the variables that are pointed at. This is termed call-by-reference; a reference, or pointer, to a variable is given to the function that is being called. This is in contrast to call-by-value, the standard way that functions are called, in which the value of a variable is given the to function being called.

The following example defines an average_sensor function which takes a port number and a pointer to an integer variable. The function will average the sensor and store the result in the variable pointed at by result.

Prefixing an argument name with * declares that the argument is a pointer.

   void average_sensor(int port, int *result)
int sum = 0;
int i;
for (I = 0; I < 10; i++) sum += analog(port);
*result = sum/10;
Notice that the function itself is declared as a void. It does not need to return anything, because it instead stores its answer in the memory location given by the pointer variable that is passed to it.

The pointer variable is used in the last line of the function. In this statement, the answer sum/10 is stored at the location pointed at by result. Notice that the * is used to assign a value to the location pointed by result.

Returning Pointers from Functions   Index

Pointers can also be returned from functions. Functions are defined to return pointers by preceeding the name of the function with a star, just like any other type of pointer declaration.

   int right,left;
int *dirptr(int dir)
if (dir==0) {
if (dir==1) {
The function dirptr returns a pointer to the global right when its argument dir is 0, a pointer to left when its argument is 1, and NULL" if its argument is other than 0 or 1.

Arrays   Index

IC supports arrays of characters, integers, long integers, floating-point numbers, structures, pointers, and array pointers (multi-dimensional arrays). While unlike regular C arrays in a number of respects, they can be used in a similar manner. The main reasons that arrays are useful are that they allow you to allocate space for many instances of a given type, send an arbitrary number of values to functions, and provide the means for iterating over a set of values.

Arrays in IC are different and incompatible with arrays in other versions of C. This incompatibility is caused by the fact that references to IC arrays are checked to insure that the reference is truly within the bounds of that array. In order to accomplish this checking in the general case, it is necessary that the size of the array be stored with the contents of the array. It is important to remember that an array of a given type and a pointer to the same type are incompatible types in IC, whereas they are largely interchangeable in regular C.

Declaring and Initializing Arrays   Index

Arrays are declared using square brackets. The following statement declares an array of ten integers:

   int foo[10];
In this array, elements are numbered from 0 to 9. Elements are accessed by enclosing the index number within square brackets: foo[4] denotes the fifth element of the array foo (since counting begins at zero).

Arrays are initialized by default to contain all zero values. Arrays may also be initialized at declaration by specifying the array elements, separated by commas, within curly braces. If no size value is specified within the square brackets when the array is declared but initialization information is given, the size of the array is determined by the number of elements given in the declaration. For example,

   int foo[]= {0, 4, 5, -8,  17, 301};
creates an array of six integers, with foo[0] equaling 0, foo[1] equaling 4, etc.

If a size is specified and initialization data is given, the length of the initialization data may not exceed the specified length of the array or an error results. If, on the other hand, you specify the size and provide fewer initialization elements than the total length of the array, the remaining elements are initialized to zero.

Character arrays are typically text strings. There is a special syntax for initializing arrays of characters. The character values of the array are enclosed in quotation marks:

   char string[]= "Hello there";
This form creates a character array called string with the ASCII values of the specified characters. In addition, the character array is terminated by a zero. Because of this zero-termination, the character array can be treated as a string for purposes of printing (for example). Character arrays can be initialized using the curly braces syntax, but they will not be automatically null-terminated in that case. In general, printing of character arrays that are not null-terminated will cause problems.

Passing Arrays as Arguments   Index

When an array is passed to a function as an argument, the array's pointer is actually passed, rather than the elements of the array. If the function modifies the array values, the array will be modified, since there is only one copy of the array in memory.

In normal C, there are two ways of declaring an array argument: as an array or as a pointer to the type of the array's elements. In IC array pointers are incompatible with pointers to the elements of an array so such arguments can only be declared as arrays.

As an example, the following function takes an index and an array, and returns the array element specified by the index:

   int retrieve_element(int index, int array[])
return array[index];
Notice the use of the square brackets to declare the argument array as a pointer to an array of integers.

When passing an array variable to a function, you are actually passing the value of the array pointer itself and not one of its elements, so no square brackets are used.

   void foo()
int array[10];
retrieve_element(3, array);
Multi-dimensional Arrays   Index

A two-dimensional array is just like a single dimensional array whose elements are one- dimensional arrays. Declaration of a two-dimensional array is as follows:

   int k[2][3];
The number in the first set of brackets is the number of 1-D arrays of int. The number in the second set of brackets is the length of each of the 1-D arrays of int. In this example, k is an array containing two 1-D arrays; k[0] is a 1-D array of color=blue>int of length 3; k[0][1] is an color=blue>int. Arrays of with any number of dimensions can be generalized from this example by adding more brackets in the declaration.

Determining the size of Arrays at Runtime   Index

An advantage of the way IC deals with arrays is that you can determine the size of arrays at runtime. This allows you to do size checking on an array if you are uncertain of its dimensions and possibly prevent your program from crashing.

Since _array_size is not a standard C feature, code written using this primitive will only be able to be compiled with IC.

The _array_size primitive returns the size of the array given to it regardless of the dimension or type of the array. Here is an example of declarations and interaction with the _array_size primitive:

   int i[4]={10,20,30};
int j[3][2]={{1,2},{2,4},{15}};
int k[2][2][2];
_array_size(i); /* returns 4 */ _array_size(j); /* returns 3 */ _array_size(j[0]); /* returns 2 */ _array_size(k); /* returns 2 */ _array_size(k[0]); /* returns 2 */
Uploading Arrays   Index

When an executing program is paused or has finished, IC can upload the values stored in any global array via the serial port. This permits collecting and recording data for purposes such as experimentation or calibration.

The IC upload array capability is accessed using the tools tab. When upload array is activated, it lists all globally declared arrays. When an array is selected, it is opened in a (modal) view window. The array can be copied to the clipboard, or saved to a TXT or CSV (comma separated values) file for import to analysis software.

Structures   Index

Structures are used to store non-homogenous but related sets of data. Elements of a structure are referenced by name instead of number and may be of any supported type. Structures are useful for organizing related data into a coherent format, reducing the number of arguments passed to functions, increasing the effective number of values which can be returned by functions, and creating complex data representations such as directed graphs and linked lists.

The following example shows how to define a structure, declare a variable of structure type, and access its elements.

   struct foo
int i;
int j;
struct foo f1;
void set_f1(int i,int j)
void get_f1(int *i,int *j)
The first part is the structure definition. It consists of the keyword struct, followed by the name of the structure (which can be any valid identifier), followed by a list of named elements in curly braces. This definition specifies the structure of the type struct foo. Once there is a definition of this form, you can use the type struct foo just like any other type. The line
    struct foo f1;
is a global variable declaration which declares the variable f1 to be of type struct foo.

The dot operator is used to access the elements of a variable of structure type. In this case, f1.i and f1.j refer to the two elements of f1. You can treat the quantities f1.i and f1.j just as you would treat any variables of type int (the type of the elements was defined in the structure declaration at the top to be int).

Pointers to structure types can also be used, just like pointers to any other type. However, with structures, there is a special short-cut for referring to the elements of the structure pointed to.

   struct foo *fptr;
void main()
In this example, fptr is declared to be a pointer to type struct foo. In main, it is set to point to the global f1 defined above. Then the elements of the structure pointed to by fptr (in this case these are the same as the elements of f1), are set. The arrow operator is used instead of the dot operator because fptr is a pointer to a variable of type struct foo. Note that (*fptr).i would have worked just as well as fptr->i, but it would have been clumsier.

Note that only pointers to structures, not the structures themselves, can be passed to or returned from functions.

Complex Initialization examples   Index

Complex types -- arrays and structures -- may be initialized upon declaration with a sequence of constant values contained within curly braces and separated by commas.

Arrays of character may also be initialized with a quoted string of characters.

For initialized declarations of single dimensional arrays, the length can be left blank and a suitable length based on the initialization data will be assigned to it. Multi-dimensional arrays must have the size of all dimensions specified when the array is declared. If a length is specified, the initialization data may not overflow that length in any dimension or an error will result. However, the initialization data may be shorter than the specified size and the remaining entries will be initialized to 0.

Following is an example of legal global and local variable initializations:

   /* declare many globals of various types */
   int i=50;
int *ptr=NULL;
float farr[3]={ 1.2, 3.6, 7.4 };
int tarr[2][4]={ { 1, 2, 3, 4 }, { 2, 4, 6, 8} };
char c[]="Hi there how are you?";
char carr[5][10]={"Hi","there","how","are","you"};
struct bar
int i;
int *p;
long j;
} b={5, NULL, 10L};
struct bar barr[2] = { { 1, NULL, 2L }, { 3 } };
/* declare locals of various types */
int foo()
int x; /* local variable x with initial value 0 */ int y= tarr[0][2]; /* local variable y with initial value 3 */ int *iptr=&i; /* local pointer to integer
which points to the global i
int larr[2]={10,20}; /* local array larr
with elements 10 and 20
struct bar lb={5,NULL,10L}; /* local variable of type
struct bar with i=5 and j=10
char lc[]=carr[2]; /* local string lc with
initial value "how"
... }
Statements and Expressions   Index

Operators act upon objects of a certain type or types and specify what is to be done to them. Expressions combine variables and constants to create new values. Statements are expressions, assignments, function calls, or control flow statements which make up C programs.

Operators   Index

Each of the data types has its own set of operators that determine which operations may be performed on them.

Integer Operations   Index

The following operations are supported on integers:

Long Integers      Index

A subset of the operations implemented for integers are implemented for long integers: arithmetic addition +, subtraction -, and multiplication *, and the integer comparison operations. Bitwise and boolean operations and division are not supported.

Floating Point Numbers   Index

IC uses a package of public-domain floating point routines distributed by Motorola. This package includes arithmetic, trigonometric, and logarithmic functions. Since floating point operations are implemented in software, they are much slower than the integer operations; we recommend against using floating point if you are concerned about performance.

The following operations are supported on floating point numbers:
  • Arithmetic. addition +, subtraction -, multiplication *, division /.
  • Comparison. greater-than >, less-than <, equality ==, greater-than-equal >=, less-than-equal <=.
  • Built-in Math Functions. A set of trigonometric, logarithmic, and exponential functions is supported. For details, go to the Library Function Descriptions. These functions are included among those itemized as "Math" functions.
Characters   Index

Characters are only allowed in character arrays. When a cell of the array is referenced, it is automatically coerced into a integer representation for manipulation by the integer operations. When a value is stored into a character array, it is coerced from a standard 16- bit integer into an 8-bit character (by truncating the upper eight bits).

Assignment Operators and Expressions   Index

The basic assignment operator is =. The following statement adds 2 to the value of a.

   a = a + 2;
The abbreviated form
   a += 2;
could also be used to perform the same operation. All of the following binary operators can be used in this fashion:
   +   -   *   /   %   <<   >>   &   ^   |
Increment and Decrement Operators   Index

The increment operator "++" increments the named variable. For example, the construction "a++" is equivalent to "a= a+1" or "a+= 1". A statement that uses an increment operator has a value. For example, the statement

   a= 3; printf("a=%d a+1=%d\n", a, ++a);
will display the text "a=3 a+1=4". If the increment operator comes after the named variable, then the value of the statement is calculated after the increment occurs. So the statement
   a= 3; printf("a=%d a+1=%d\n", a, a++);
would display "a=3 a+1=3" but would finish with a set to 4. The decrement operator "--" is used in the same fashion as the increment operator.

Data Access Operators   Index

A single ampersand preceding a variable, an array reference, or a structure element reference returns a pointer to the location in memory where that information is being stored. This should not be used on arbitrary expressions as they do not have a stable place in memory where they are being stored.
A single * preceeding an expression which evaluates to a pointer returns the value which is stored at that address. This process of accessing the value stored within a pointer is known as dereferencing.
An expression in square braces following an expression which evaluates to an array (an array variable, the result of a function which returns an array pointer, etc.) checks that the value of the expression falls within the bounds of the array and references that element.
A dot between a structure variable and the name of one of its fields returns the value stored in that field.
An arrow between a pointer to a structure and the name of one of its fields in that structure acts the same as a dot does, except it acts on the structure pointed at by its left hand side. Where f is a structure of a type with i as an element name, the two expressions f.i and (&f)->i are equivalent.

Precedence and Order of Evaluation   Index

The following table summarizes the rules for precedence and associativity for the C operators. Operators listed earlier in the table have higher precedence; operators on the same line of the table have equal precedence.
Operator   Associativity  
  () [] left to right
  ! ~ ++ -- - (<type>)   right to left
  * / % left to right
  + - left to right
  << >> left to right
  < <= > >= left to right
  == != left to right
  & left to right
  ^ left to right
  | left to right
  && left to right
  || right to left
  = += -= etc. right to left
  , left to right

Control Flow   Index

IC supports most of the standard C control structures.

Statements and Blocks   Index

A single C statement is ended by a semicolon. A series of statements may be grouped together into a block using curly braces. Inside a block, local variables may be defined. Blocks may be used in place of statements in the control flow constructs.

If-Else   Index

The if else statement is used to make decisions. The syntax is:

   if (<expression>)
else <statement-2>
<expression> is evaluated; if it is not equal to zero (e.g., logic true), then <statement-1> is executed.

The else clause is optional. If the if part of the statement did not execute, and the else is present, then <statement-2> executes.

While   Index

The syntax of a while loop is the following:

   while (<expression>)
while begins by evaluating <expression>. If it is false, then <statement> is skipped. If it is true, then <statement> is evaluated. Then the expression is evaluated again, and the same check is performed. The loop exits when <expression> becomes zero.

One can easily create an infinite loop in C using the while statement:

   while (1)

Do-While   Index

The syntax of a do-while loop is the following:

while (<expression>);

The equivalent while loop would be the following:

while (<expression>)

For   Index

The syntax of a for loop is the following:

   for (<expr-1>;<expr-2>;<expr-3>)
The for construct is equivalent to the following construct using while:
while (<expr-2>)
Typically, <expr-1> is an assignment, <expr-2> is a relational expression, and <expr-3> is an increment or decrement of some manner. For example, the following code counts from 0 to 99, printing each number along the way:
   int i;
for (i = 0; i < 100; i++)
printf("%d\n", i);

Switch   Index

The syntax of a switch block is as follows:

   switch (int)
case const1:
<statement list1>
case const2:
<statement list2>
<statement list3>

The switch construct takes an integer variable as input, and compares it to each case listed. The first matching const is selected, and execution begins there. The break is optional, and if no break is found then execution continues through each following statement. Also note that each case has a list of single statements, as opposed to a block enclosed in curly braces.

Here's an example of how a switch might be used:

   int i = 1;
case 0:
printf("Case 0\n");
case 1:
printf("Case 1\n");

Since i is equal to 1, the text "Case 1" will be printed to the screen. If i were equal to 0, "Case 0" would be printed. If i were any number besides 0 or 1, "Default" would be printed.

Break   Index

Use of the break statement provides an early exit from a while, do-while or for loop. The break statement can also provide an exit from a switch block.

LCD Screen Printing   Index

IC has a version of the C function printf for formatted printing to the LCD screen.

The syntax of printf is the following:

   printf(<format-string>, <arg-1> , ... , <arg-N>);
This is best illustrated by some examples.

Printing Examples   Index

Example 1: Printing a message   PM Index

The following statement prints a text string to the screen.
   printf("Hello, world!\n");
In this example, the format string is simply printed to the screen. The character \n at the end of the string signifies end-of-line. When an end-of-line character is printed, the LCD screen will be cleared when a subsequent character is printed. Thus, most printf statements are terminated by a \n.

Example 2: Printing a number   Index

The following statement prints the value of the integer variable x with a brief message.
   printf("Value is %d\n", x);
The special form %d is used to format the printing of an integer in decimal format.

Example 3: Printing a number in binary   Index

The following statement prints the value of the integer variable x as a binary number.
   printf("Value is %b\n", x);
The special form %b is used to format the printing of an integer in binary format. Only the low byte of the number is printed.

Example 4: Printing a floating point number   Index

The following statement prints the value of the floating point variable n as a floating point number.
   printf("Value is %f\n", n);
The special form %f is used to format the printing of floating point number.

Example 5: Printing two numbers in hexadecimal format   Index

   printf("A=%x  B=%x\n", a, b);
The form %x formats an integer to print in hexadecimal.

Formatting Command Summary   Index

 Format Command  Data Type Description
  %d   int   decimal number
  %x   int   hexadecimal number
  %b   int   low byte as binary number
  %l   long   long (decimal) integer
  %c   int   low byte as ASCII character  
  %f   float   floating point number
  %s   char array     char array (string)
Special Note
  • Depending on the display being used, the upper right position of the menu screens has a red system "heartbeat." This character continuously blinks between a large and small heart when the board is operating properly. If the character stops blinking, the board has failed. The console screen supports display characters in 14 lines of 28 characters. Printing of long integers is supported on the console. In addition characters can be placed in random positions on the screen (see display clear(), display_set_xy(), and display_get_xy() function descriptions).

Preprocessor   Index

The preprocessor processes a file before it is sent to the compiler. The IC preprocessor allows definition of macros, and conditional compilation of sections of code. Using preprocessor macros for constants and function macros can make IC code more efficient as well as easier to read. Using #if to conditionally compile code can be very useful, for instance, for debugging purposes.

The special preprocessor command #use has been included to allow programs to cause a program to download to initiate the download of stored programs that are not in the IC library. For example, suppose you have a set of stored programs in a file named "mylib.ic", some of which you need for your current program to work.

   /* load my library */
   #use "mylib.ic"

   void main()
char s[32] = "text string wrapping badly\n";
fix (s); /* apply my fix function to s and print it */ printf(s);
Preprocessor Macros   Index

Preprocessor macros are defined by using the #define preprocessor directive at the start of a line. A macro is local to the file in which it is defined. The following example shows how to define preprocessor macros.

  #define RIGHT_MOTOR 0
#define LEFT_MOTOR 1
#define GO_RIGHT(power) (motor(RIGHT_MOTOR,(power)))
#define GO_LEFT(power) (motor(LEFT_MOTOR,(power)))
#define GO(left,right) {GO_LEFT(left); GO_RIGHT(right);}
void main()
Preprocessor macro definitions start with the #define directive at the start of a line, and continue to the end of the line. After #define is the name of the macro, such as RIGHT_MOTOR. If there is a parenthesis directly after the name of the macro, such as the GO_RIGHT macro has above, then the macro has arguments. The GO_RIGHT and GO_LEFT macros each take one argument. The GO macro takes two arguments. After the name and the optional argument list is the body of the macro.

Each time a macro is invoked, it is replaced with its body. If the macro has arguments, then each place the argument appears in the body is replaced with the actual argument provided.

Invocations of macros without arguments look like global variable references. Invocations of macros with arguments look like calls to functions. To an extent, this is how they act. However, macro replacement happens before compilation, whereas global references and function calls happen at run time. Also, function calls evaluate their arguments before they are called, whereas macros simply perform text replacement. For example, if the actual argument given to a macro contains a function call, and the macro instantiates its argument more than once in its body, then the function would be called multiple times, whereas it would only be called once if it were being passed as a function argument instead.

Appropriate use of macros can make IC programs and easier to read. It allows constants to be given symbolic names without requiring storage and access time as a global would. It also allows macros with arguments to be used in cases when a function call is desirable for abstraction, without the performance penalty of calling a function.

Conditional compilation   Index

It is sometimes desirable to conditionally compile code. The primary example of this is that you may want to perform debugging output sometimes, and disable it at other times. The IC preprocessor provides a convenient way of doing this by using the #ifdef directive.

   void go_left(int power)
#ifdef DEBUG
printf("Going Left\n");
#endif }
In this example, when the macro DEBUG is defined, the debugging message "Going Left" will be printed and the board will beep each time go_left is called. If the macro is not defined, the message and beep will not happen. Each #ifdef must be follwed by an #endif at the end of the code which is being conditionally compiled. The macro to be checked can be anything, and #ifdef blocks may be nested.

Unlike regular C preprocessors, macros cannot be conditionally defined. If a macro definition occurs inside an #ifdef block, it will be defined regardless of whether the #ifdef evaluates to true or false. The compiler will generate a warning if macro definitions occur within an #ifdef block.

The #if, #else, and #elif directives are also available, but are outside the scope of this document. Refer to a C reference manual for how to use them.

Comparison with regular C preprocessors   Index

The way in which IC deals with loading multiple files is fundamentally different from the way in which it is done in standard C. In particular, when using standard C, files are compiled completely independently of each other, then linked together. In IC, on the other hand, all files are compiled together. This is why standard C needs function prototypes and extern global definitions in order for multiple files to share functions and globals, while IC does not.

In a standard C preprocessor, preprocessor macros defined in one C file cannot be used in another C file unless defined again. Also, the scope of macros is only from the point of definition to the end of the file. The solution then is to have the prototypes, extern declarations, and macros in header files which are then included at the top of each C file using the #include directive. This style interacts well with the fact that each file is compiled independent of all the others.

However, since declarations in IC do not file scope, it would be inconsistent to have a preprocessor with file scope. Therefore, for consistency it was desirable to give IC macros the same behavior as globals and functions. Therefore, preprocessor macros have global scope. If a macro is defined anywhere in the files loaded into IC, it is defined everywhere. Therefore, the #include and #undef directives did not seem to have any appropriate purpose, and were accordingly left out.

The fact that #define directives contained within #if blocks are defined regardless of whether the #if evaluates to be true or false is a side effect of making the preprocessor macros have global scope.

Other than these modifications, the IC preprocessor should be compatible with regular C preprocessors.

The IC Library File   Index

Library files provide standard C functions for interfacing with hardware on the robot controller board. These functions are written either in C or as assembly language drivers. Library files provide functions to do things like control motors, make tones, and input sensors values.

IC automatically loads the library file every time it is invoked. Depending on which board is being used, a different library file will be required. IC may be configured to load different library files as its default; IC will automatically load the correct library for the board you're using at the moment.

Separate documentation covers all library functions available for the Handy Board, the Lego RCX, and the XBC; if you have another board, see your owner's manual for documentation.

To understand better how the library functions work, study of the library file source code is recommended; e.g., the main library file for the Handy Board is named lib_hb.ic.

For convenience, a description of some of the more commonly used library functions follows.

Commonly Used IC Library Functions   Index

/* returns 0 if the switch attached to the port is open and
returns 1 if the switch is closed. Digital ports are numbered
7-15. Typically used for bumpers or limit switches.
/* returns the analog value of the port (a value in the range 0-255).
Analog ports on the handy board are numbered 2-6 and 16-23. Light
sensors and range sensors are examples of sensors you would
use in analog ports (only on Handy Board).
/* waits specified number of seconds */ beep();
/* causes a beep sound */ tone(<float_frequency>, <float_secs>)
/* plays at specified frequency for specified time (seconds) */ printf(<string>, <arg1>, <arg2>, ... );
/* prints <string>. If the string contains % codes then the <args>
after the string will be printed in place of the % codes in the
format specified by the code. %d prints a decimal number. %f
prints a floating point number. %c prints a character, %b prints
an integer in binary, %x prints an integer in hexadecimal.
motor(<motor_#>, <speed>)
/* controls the motors. <motor_#> is an integer between 0 and 3 (1
less for RCX). <speed> is an integer between -100 and 100 where 0
means the motor is off and negative numbers run the motor in the
reverse direction
/* turns on the motor specified (direction is determined by plug
/* turns on the motor specified in the opposite direction from fd */ off(<motor_#>);
/* turns off the motor specified */ ao();
/* turns all motor ports off */
Processes   Index

Processes work in parallel. Each process, once it is started, will continue until it finishes or until it is killed by another process using the kill_process(<process_id)>); statement. Each process that is active gets 50ms of processing time. Then the process is paused temporarily and the next process gets its share of time. This continues until all the active process have gotten a slice of time, then it all repeats again. From the user's standpoint it appears that all the active processes are running in parallel.

Processes can communicate with one another by reading and modifying global variables. The globals can be used as semaphores so that one process can signal another. Process IDs may also be stored in globals so that one process can kill another when needed.

Up to 4 processes initiated by the start_process() library function can be active at any time.

The library functions for controlling processes are:

start_process(<function_name>(<arg1>, <arg2>, . . .));
/* start_process returns an integer that is the <process_id>
and starts the function <function_name> as a separate
/* when placed in a function that is used as a process this
will cause that process to give up the remainder of its time
slice whenever defer is called
/* this will terminate the process specified by the
Encoders   Index

The enable_encoder() library function is used to start a process which updates the transition count for the encoder specified. The encoder library functions are designed for sensors connected to (digital) ports 8-15. Every enabled encoder uses a lot of the processor -- so don't enable an encoder unless you are going to use it, and never put an enable statement inside of a loop.

/* turns on the specified encoder (which are plugged into digital
ports 8-15). This should be done only once - never enable an
already enabled encoder. If an encoder is not enabled
read_encoder will always return 0.
/* turns off the specified encoder */ reset_encoder(<port#>)
/* sets the specified encoder value to 0 */ read_encoder(<port#>)
/* returns an int that is the current value of the specified


Light Sensor

Infrared "Top Hat" Reflectance Sensor

Infrared "E.T." Distance Sensor
(high-impedance analog)

Touch Sensors

Infrared "Break Beam" Sensor

(Ultrasonic Rangefinder)

Light Sensor (analog)

Infrared "Top Hat" Reflectance Sensor (analog)

Infrared "E.T." Distance Sensor (high-impedance analog)

Touch Sensors (digital)

Infrared "Break Beam" Sensor (digital)

Sonar (Ultrasonic Rangefinder)

XBC Library Function Descriptions

(alphabetic order)
a_button    [Category: Sensors]   
Format: int a_button()
Reads the value (0 or 1) of the A button (button #1).
alloff    [Category: Motors]   
Format: void alloff()
Turns off all motors. ao is a short form for alloff.
analog    [Category: Sensors]   
Format: int analog(int p)
Returns the value of the sensor installed at the port numbered p. The result is an integer between 0 and 255. The function can be used with analog ports 0 through 6 (see note below on port 7). Ports 0 and 1 are floating (used for sensors such as an optical range finder). If the analog() function is applied to a port that is implemented digitally in hardware, then the value 255 is returned if the hardware digital reading is 1 (as if a digital switch is open, and the pull up resistors are causing a high reading), and the value 0 is returned if the hardware digital reading is 0 (as if a digital switch is closed and pulling the reading near ground). Ports are numbered as marked. Since ports 0 and 1 are floating, the value cannot be predicted without a sensor inserted. NOTE: Port 7 is used internally to monitor battery voltage and so is not available for other uses.
analog12    [Category: Sensors]   
Format: int analog12(int p)
12-bit version of the analog function. The returned value is in the range 0 to 4095 rather than 0 to 255.
any_button    [Category: Sensors]   
Format: int any_button()
Returns 1 if any button (other than START or SELECT) is pressed.
ao    [Category: Motors]   
Format: void ao()
Turns off all motors.
atan    [Category: Math]   
Format: float atan(float angle)
Returns the arc tangent of the angle. Angle is specified in radians; the result is in radians.
b_button    [Category: Sensors]   
Format: int b_button()
Reads the value (0 or 1) of the B button (button #2).
beep    [Category: Sound]   
Format: void beep()
Produces a tone of 500 Hertz for a period of 0.3 seconds. Returns when the tone is finished.
beeper_off    [Category: Sound]   
Format: void beeper_off()
Turns off the beeper.
beeper_on    [Category: Sound]   
Format: void beeper_on()
Turns on the beeper at last frequency selected by the former function. The beeper remains on until the beeper_off function is executed.
bk    [Category: Motors]   
Format: void bk(int m)
Turns motor m on full speed in the backward direction.

block_motor_done   [Category: Motors]   
Format: void block_motor_done(int m)
Function does not return until specified motor completes any executing speed or position control moves.

bmd   [Category: Motors]   
Format: void bmd(int m)
Function does not return until specified motor completes any executing speed or position control moves.
button_held    [Category: Sensors]   
Format: int button_held(int button_nbr, int state1, int state2)
state1 and state2 are bit vectors obtained by using button_state. The returned value is 1 if the addressed button was pressed at both state1 and state2.
button_hit    [Category: Sensors]   
Format: int button_hit(int button_nbr, int state1, int state2)
state1 and state2 are bit vectors obtained by using button_state. The returned value is 1 if the addressed button was not pressed at state1 but is pressed at state2.
button_released    [Category: Sensors]   
Format: int button_hit(int button_nbr, int state1, int state2)
state1 and state2 are bit vectors obtained by using button_state. The returned value is 1 if the addressed button was pressed at state 1, but is not pressed at state2.
button_state    [Category: Sensors]   
Format: int button_state()
Returns a bit vector of the state of all the buttons. The check_button function uses this to return the value of a button (0 or 1)
button_transit    [Category: Sensors]   
Format: int button_transit(int button_nbr, int state1, int state2)
state1 and state2 are bit vectors obtained by using button_state. The returned value is 1 if the addressed button was pressed or released in going from state1 to state2.
check_button    [Category: Sensors]   
Format: int check_button(int button_nbr)
Reads the value (0 or 1) of the button specified. A=1, B=2, R=256, L=512, right=16, left=32, up=64, down=128.
choose_button    [Category: Sensors]   
Format: int choose_button()
Returns value of button labeled A.
   /* wait for button to be pressed; then wait for it to be
      released so that button press is debounced */

   while (!choose_button()) {}
   while (choose_button()) {}
clear_motor_position_counter    [Category: Motors]   
Format: void clear_motor_position_counter(int motor_nbr)
Reset the position counter for the motor specified to 0.
cos    [Category: Math]   
Format: float cos(float angle)
Returns cosine of angle. Angle is specified in radians; result is in radians.
defer    [Category: Processes]   
Format: void defer()
Makes a process swap out immediately after the function is called. Useful if a process knows that it will not need to do any work until the next time around the scheduler loop. defer() is implemented as a C built-in function.
digital    [Category: Sensors]   
Format: int digital(int p)
Returns the value of the sensor in sensor port p, as a true/false value (1 for true and 0 for false). Sensors are expected to be active low, meaning that they are valued at zero volts in the active, or true, state. Thus the library function returns the inverse of the actual reading from the digital hardware: if the reading is zero volts or logic zero, the digital() function will return true. Valid for digital ports 8-15.
disable_encoder    [Category: Sensors]   
Format: void disable_encoder(int p)
Disables the given encoder and prevents it from counting. Each encoder uses processing time every time it receives a pulse while enabled, so they should be disabled when you no longer need the encoder's data.
disable_extra_encoder    [Category: Sensors]   
Format: void disable_extra_encoder(int p)
Disables encoder processing for the addressed extra port (16-23). Requires use of a dongle to access port).
disable_servos    [Category: Motors]   
Format: void disable_servos()
Disables the servo motor ports (powers down all servo motors).
display_clear    [Category: Output]   
Format: void display_clear()
Clears the display screen to blank.
display_get_xy    [Category: Output]   
Format: void display_get_xy(*int x, *int)
Assigns to x and y the current (column,row) coordinates on the display screen for the next printf. o<=column<=27 and 0<=row<=13
display_set_xy    [Category: Output]   
Format: void display_set_xy(int x, int)
Positions the position on the display screen for the next printf at the (column,row) coordinates given by x and y.
down_button    [Category: Sensors]   
Format: int down_button()
Reads the value (0 or 1) of the move down button (button #128).
enable_encoder    [Category: Sensors]   
Format: void enable_encoder(int p)
Enables the given encoder to start counting pulses and resets its counter to zero. By default encoders start in the disabled state and must be enabled before they start counting.
enable_extra_encoder    [Category: Sensors]   
Format: void enable_extra_encoder(int p)
Enables encoder processing for the addressed extra port (16-23). Requires use of a dongle to access port).
enable_servos    [Category: Sensors]   
Format: void enable_servos()
Enables all servo motor ports.
escape_button    [Category: Sensors]   
Format: int escape_button()
Returns value of button labeled B: 1 if pressed and 0 if released. Example:
   /* wait until escape button pressed */
   while (!escape_button()) {}
exp10    [Category: Math]   
Format: float exp10(float num)
Returns 10 to the num power.
exp    [Category: Math]   
Format: float exp(float num)
Returns e to the num power.
extra_digital    [Category: Sensors]   
Format: int extra_digital(int p)
Same as digital except applies to ports 16-23. A "dongle" is usually used to access these ports.
fd    [Category: Motors]   
Format: void fd(int m)
Turns motor m on full in the forward direction.
freeze    [Category: Motors]   
Format: void freeze(int m)
Freezes motor m (prevents continued motor rotation, in contrast to off, which allows the motor to "coast").
get_motion_acceleration    [Category: Motors]   
Format: int get_motion_acceleration(int m)
It is recommended that the default motion acceleration set by firmware on bootup be used. The function returns the current value used for motor acceleration for motor m.
get_motor_done    [Category: Motors]   
Format: int get_motor_done(int m)
Returns whether the motor has finished a move with specified position.
get_motor_position_counter    [Category: Motors]   
Format: long get_motor_position_counter(int m)
Returns the current motor position value for motor m (a value which is continually being updated for each motor using back EMF; a typical discrimination for a given motor is on the order of 1100 position "ticks" per rotation)
get_scaled_sonar_value    [Category: Sensors]   
Format: int get_scaled_sonar_value(int port)
Returns the current value of the addressed sonar, scaled accorrding to the scale_sonar function. Routine for non-blocking sonar (sonar function blocks).
get_servo_position    [Category: Motors]   
Format: int get_servo_position(int srv)
Returns the position value of the servo in port srv. The value is in the range 0 to 255. There are 4 servo ports (0, 1, 2, 3).
get_sonar_ping_time    [Category: Sensors]   
Format: int get_sonar_ping_time(int port)
Routine for non-blocking sonar (sonar function blocks).
hog_processor    [Category: Processes]   
Format: void hog_processor()
Allocates an additional 256 milliseconds of execution to the currently running process. If this function is called repeatedly, the system will wedge and only execute the process that is calling hog_processor(). Only a system reset will unwedge from this state. Needless to say, this function should be used with extreme care, and should not be placed in a loop, unless wedging the machine is the desired outcome.
kill_process    [Category: Processes]   
Format: void kill_process(int pid);
The kill_process function is used to destroy processes. Processes are destroyed by passing their process ID number to kill_process. If the return value is 0, then the process was destroyed. If the return value is 1, then the process was not found. The following code shows the main process creating a check_sensor process, and then destroying it one second later:
    void main() {
int pid;
l_button    [Category: Sensors]   
Format: int l_button()
Reads the value (0 or 1) of the L (shoulder) button (button #512).
left_button    [Category: Sensors]   
Format: int left_button()
Reads the value (0 or 1) of the move left button (button #32).
log10    [Category: Math]   
Format: float log10(float num)
Returns the logarithm of num to the base 10.
log    [Category: Math]   
Format: float log(float num)
Returns the natural logarithm of num.

mav    [Category: Motors]   
Format: void mav(int m, int vel)
This function is the same as move_at_velocity
motor    [Category: Motors]   
Format: void motor(int m, int p)
Turns on motor m at scaled PWM duty cycle percentage  p. Power levels range from 100 for full on forward to -100 for full on backward.
move_at_velocity    [Category: Motors]   
Format: void move_at_velocity(int m, int vel)
Moves motor m at velocity vel indefinitely. The velocity range is -1000 to 1000 ticks per second.
move_relative_position    [Category: Motors]   
Format: void move_relative_position(int m, int speed, long pos)
Moves motor m at velocity vel from its current position curr_pos to curr_pos + pos. The speed range is 0 to 1000 ticks per second. Example:
move_to_position    [Category: Motors]   
Format: void move_to_position(int m, int speed, long pos)
Moves motor m at velocity vel from its current position curr_pos to pos. The speed range is 0 to 1000. Note that if the motor is already at pos, the motor doesn't move.
mrp    [Category: Motors]   
Format: void mrp(int m, int vel, long pos)
This function is the same as move_relative_position.

mtp   [Category: Motors]   
Format: void mtp(int m, int vel, long pos)
This function is the same as move_to_position.
mseconds    [Category: Time]   
Format: long mseconds()
Returns the count of system time in milliseconds. Time count is reset by hardware reset (i.e., pressing reset switch on board) or the function reset_system_time().
mseconds() is implemented as a C primitive (not as a library function).
msleep    [Category: Time]   
Format: void msleep(long msec)
Waits for an amount of time equal to or greater than msec milliseconds. msec is a long integer.
   /* wait for 1.5 seconds */ msleep(1500L);
off    [Category: Motors]   
Format: void off(int m)
Turns off motor m.
power_level    [Category: System]   
Format: float power_level()
Returns the current power level in volts.
printf    [Category: Output]   
Format: void printf(char s[], . . .)
Prints the contents of the string referenced by s to the cursor position on the screen.
See the manual above for more details.
r_button    [Category: Sensors]   
Format: int r_button()
Reads the value (0 or 1) of the R (shoulder) button (button #256).
random    [Category: Math]   
Format: int random(int m)
"Random" numbers are generated by peeking at system clock; input m is from 2 to 32767.
read_encoder    [Category: Sensors]   
Format: int read_encoder(int p)
Returns the number of pulses counted by the given encoder since it was enabled or since the last reset, whichever was more recent. The port p is in the range 8-15.
read_extra_encoder    [Category: Sensors]   
Format: int read_extra_encoder(int p)
Returns the number of pulses counted by the given encoder since it was enabled or since the last reset, whichever was more recent. The port p is in the range 16-23.
reset_encoder    [Category: Sensors]   
Format: void reset_encoder(int p)
Resets the counter of the given encoder to zero. For an enabled encoder, it is more efficient to reset its value than to use enable_encoder() to clear it. The port p is in the range 8-15.
reset_extra_encoder    [Category: Sensors]   
Format: int reset_extra_encoder(int p)
Resets the counter of the given encoder to zero. For an enabled encoder, it is more efficient to reset its value than to use enable_extra_encoder() to clear it. The port p is in the range 16-23.
right_button    [Category: Sensors]   
Format: int right_button()
Reads the value (0 or 1) of the move right button (button #16).
scale_sonar    [Category: Sensors]   
Format: int scale_sonar(int microsecs)
This is the scaling function for the sonar function, returning the approximate millimeters corresponding to the number of microseconds for a signal round trip.
seconds    [Category: Time]   
Format: float seconds()
Returns the count of system time in seconds, as a floating point number. Resolution is one millisecond.
send_sonar_ping    [Category: Sensor]   
Format: void send_sonar_ping(int p)
Routine for non-blocking sonar (sonar function blocks) - sends a ping on sonar port.
set_beeper_pitch    [Category: Sound]   
Format: void set_beeper_pitch(float frequency)
Sets the beeper tone to be frequency (measure in Hz). The beeper_on function is then used to turn the beeper on.
set_motion_acceleration    [Category: Motors]   
Format: void set_motion_acceleration(int m, int accel)
It is recommended that the default motion acceleration set by firmware on bootup be used. The function sets the current value used for motor acceleration for motor m.
set_motor_position_counter    [Category: Motors]   
Format: void set_motor_position_counter(int m, long pos)
Sets the current motor position value for motor m (a value which is continually being updated for each motor using back EMF; a typical discrimination for a given motor is on the order of 1100 position "ticks" per rotation)
set_pid_gains    [Category: Motors]   
Format: int set_pid_gains(int kp, int ki, int kd)
set_servo_position    [Category: motor]   
Format: int set_servo_position(int srv, int pos)
Sets the position value of the servo in port srv. The value of pos must be in the range 0 to 255. There are 4 servo ports (0, 1, 2, 3).
set_sonar_port    [Category: sensor]   
Format: int set_sonar_port(int p)
Routine for non-blocking sonar (sonar function blocks).

setpwm    [Category: Motors]   
Format: int setpwm(int m, int dutycycle)
Runs motor m at duty cycle dutycycle (values -100 to 100)
sin    [Category: Math]   
Format: float sin(float angle)
Returns the sine of angle. angle is specified in radians; result is in radians.
sleep    [Category: Time]   
Format: void sleep(float sec)
Waits for an amount of time equal to or slightly greater than sec seconds. sec is a floating point number. Example:
   /* wait for 1.5 seconds */ sleep(1.5);
sonar    [Category: Sensors]   
Format: int sonar()
Returns the approximate distance in mm.
sqrt    [Category: Math]   
Format: float sqrt(float num)
Returns the square root of num.
start_process    [Category: Processes]   
Format: int start_process(<function call>);
The start_process function is used to start a process, which then runs in parallel with other active processes. The system keeps track of each running process by assigning a process ID number to it. start_process returns the process ID number for each process it starts. The process runs until it finishes or until it is terminated by kill_process. Up to 4 processes (in addition to main) can by started using start_process. The following code shows the main process creating a check_sensor process, and then destroying it one second later:
    void main() {
int pid;
tan    [Category: Math]   
Format: float tan(float angle)
Returns the tangent of angle. angle is specified in radians; result is in radians.
tone    [Category: Sound]   
Format: void tone(float frequency, float length)
Produces a tone at pitch frequency (measured in Hertz) for length seconds. Returns when the tone is finished. Both frequency and length are floats.
up_button    [Category: Sensors]   
Format: int up_button()
Reads the value (0 or 1) of the move up button (button #64).

  • To use any camera routines, be sure to put
      #use "xbccamlib.ic"
    at the top of your file
  • You must call
     void init_camera();
    to initialize the camera before any other camera functions will work

Tracking APIs

  • Use
     int track_is_new_data_available();
    to determine if tracking data is available which is newer than the data processed by the last call to track_update().
  • Use
     void track_update();
    to process tracking data for a new frame and make it available for retrieval by the following calls.
  • Use
     long track_get_frame();
    to return value is the frame number used to generate the tracking data.
  • Use
     int track_count(int ch);
    to return the number of blobs available for the channel ch, which is a color channel numbered 0 through 2.
  • Use the following functions of the form
     int track_property(int ch, int i);
    to return the value of a given property for the blob from channel ch (range 0-2), index i (range 0 to track_count(ch)-1). Fill in track_property from one of the following:
    • track_size
    gets the number of pixels in the blob, note that this maxes out (saturates) at 32,767 if the area gets that large
    • track_x
    gets the pixel x coordinate of the centroid of the blob
    • track_y
    gets the pixel y coordinate of the blob
    (note: 0,0 is the upper left; 356x292 is the lower right)
    • track_confidence
    gets the confidence for seeing the blob as a percentage of the blob pixel area/bounding box area (range 0-100, low numbers bad, high numbers good)
    • track_bbox_left
    gets the pixel x coordinate of the leftmost pixel in the blob
    • track_bbox_right
    gets the pixel x coordinate of the rightmost pixel in the blob
    • track_bbox_top
    gets the pixel y coordinate of the topmost pixel in the blob
    • track_bbox_bottom
    gets the pixel y coordinate of the bottommost pixel in the blob
    • track_bbox_width
    gets the pixel x width of the bounding box of the blob. This is equivalent to track_bbox_right - track_bbox_left
    • track_bbox_height
    gets the pixel y height of the bounding box of the blob. This is equivalent to track_bbox_bottom - track_bbox_top
  • Use
     void track_set_ch_enable(int ch, int val);
     int track_get_ch_enable(int ch);
    to enable or disable processing tracking data for a particular channel ch (range 0-2).  The value passed into val or returned by track_get_ch_enable is 0=disabled, 1=enabled. All channels are enabled by default.  Disabling unused channels is not required, but can increase performance. 
  • Use
     void track_enable_orientation();
     void track_disable_orientation();
     void track_set_orientation_enable(int val)();
     int track_orientation_enabled();
    to enable or disable orientation calculation, or get the current value of this setting (0=disabled, 1=enabled). This is disabled by default, and takes significant extra computation when enabled.
  • When orientation calculation is enabled, use the following functions of the form
     float track_property(int ch, int i);
    to return the value of a given orientation-related property for the blob from channel ch (range 0-2), index i (range 0 to track_count(ch)-1). Fill in track_property from one of the following:
    • track_angle
    gets the angle in radians of the major axis of the blob. Zero is horizontal and when the left end is higher than the right end the angle will be positive. The range is -PI/2 to +PI/2.
    • track_major_axis
    gets the length in pixels of the major and minor axes of the bounding ellipse
  • Use
     void track_set_minarea(int minarea);
     int track_get_minarea();
    to set or retrieve the minimum area of a blob necessary to consider it valid. Blobs with area below minarea are ignored, and only blobs with area above minarea are returned by the above calls. Default value of min area is 100. The min area can be set interactively using the vision menus as well.
  • Use
     void track_show_display(int show_processed, int frameskip, int channel_mask);
    to show tracking results on the Gameboy display.
    • show_processed controls what type of video is displayed. If it is zero then raw video will be displayed, meaning that the video will be shown as it comes from the camera; if it is non-zero then processed video will be shown, meaning that pixels matching each color channel will be shown as a different color, and pixels matching no color channel will be shown as black.
    • frameskip controls how many frames of video are skipped between display updates. Smaller numbers will result in smoother video, but will heavily load the system and cause other computation to happen more slowly. Larger numbers will result in jerkier video, but allow other computaion more time to execute.
    • channel_mask controls which channels blob tracking data and/or processed video is shown for. The LSB controls channel 0, the next most significant bit controls channel 1, etc. A 1 in each bit position means to show that channel, and a 0 means to not show it. For example, 7 (0b111) shows all channels, 4 (0b100) shows just channel 2, etc.
    A user may exit out of tracking display mode by hitting the B button on the Gameboy, which is consistent with the way display modes are exited when using the menu system.

Camera Configuration APIs

  • Concepts:
    • White Balance refers to the "color temperature" the camera uses in converting the incoming light into pixel values.  This is necessary because different light sources can contain a significantly different balance of red and blue components.  For example, the sun and incandescent lights are much redder, and fluorescent lights are much bluer.  Human brains compensate for changes in lighting color very quickly, to the point where we are mostly unaware that the issue exists. 

      Cameras, however, need to use explicit mechanisms to try to compensate for these changes so that things in the image look "right" to humans, and more importantly for color segmentation, so that the HSV values reported by the camera when looking at a given object can be fairly uniform when seen in a range of different lighting sources. 

      By default cameras turn on Auto White Balance (AWB) and dynamically adjust their color temperature to keep the amounts of red and blue in the field of view roughly balanced.  This is fine if the content of the field of view is roughly balanced between red and blue and if the goal is to look good to humans in changing, arbitrary lighting situations.  However, when trying to do color tracking, dynamically changing color temperature is generally counter productive. 

      Instead, you should use the Vision/Camera Config menu and press the Start button to interactively calibrate the white balance while pointing the camera at a white sheet of paper.  This will adjust the Red and Blue components of the color temperature until the amount of each in the scene balances, then turn off AWB to lock those values in.  After this procedure, it's a good idea to go to the Vision/Flash Memory menu, select "Setting: < Camera Config >", and then "Save to Flash".

    • Exposure (range 0-154) refers to the amount of time during each frame that the camera spends allowing light to be detected.  If the light is very bright this will be a small amount of time, since in bright light it doesn't take long to accumulate all the light the camera's detector can handle.  If the light is dim then this will be a larger amount of time.  By default the camera enables Automatic Exposure Control (AEC) and dynamically adjusts this value to maintain a constant relative percentage of "bright" and "dark" pixels.  If you disable AEC then the Exposure will stay at whatever value it was last set to until AEC is enabled again. 
    • Gain (range 0-248) controls how much the raw image integrated from the incoming light is multiplied in order to generate the pixel values reported by the camera.  If the light is bright enough, Gain should be zero.  When the light is not bright enough, Gain has to be higher in order to compensate or the image will be too dark to be useful, but the quality of the image goes down and looks grainier.  By default the camera enables Automatic Gain Control (AGC) and dynamically adjusts this value to maintain a constant relative percentage of "bright" and "dark" pixels.  If you disable AGC then the Gain will stay at whatever value it was last set to until AGC is enabled again. 
    • Exposure/Gain xpoSetting:
      • The camera will report the Exposure and Gain values which it is currently using independent of whether AEC or AGC are enabled.
      • The user can directly set the Gain value (which also implicitly disables AGC), but the camera does not support not support directly setting the Exposure value.
      • There are two parameters which allow the user to adjust the way the camera dynamically adjusts its Exposure and Gain
        • Auto Exposure Ratio (AERatio) (range 1- 254, default=65) controls the percentage of "bright" versus "dark" pixels which it tries to maintain: 1 = Maintain 0.5% "bright" pixels, 65 = 25% "bright", 254 = 99.5% "bright".  The net effect of this is that low AERatio values make the image look darker, and high values make the image look brighter.
        • Exposure Reference Level (ExpRL) (range 0-224, default 160) selects the reference level voltage used for automatic setting of Exposure and Gain.  Higher values make the image look brighter, and lower values make it look darker.  This is actually a 3-bit value in the most significant 3 bits of a byte, so value changes are in increments of 32.
      • When AEC and AGC are both enabled, the camera will set Gain to zero if the light is bright enough and modify Exposure to achieve the desired percentage of "bright" pixels given the current values of AERatio and ExpRL.  As the light level decreases the camera will increase Exposure until it hits the maximum value (154), then modify Gain as much as it needs to to achieve its goals or until it hits the maximum value (248).
  • Use
     int camera_get_awb();
     int camera_set_awb(int enable);
    to get or set whether or not Auto White Balance is enabled (0=disabled, 1=enabled).
  • Use
     int camera_get_wb_color_temp(int color[]);
     int camera_set_wb_color_temp(int color[]);
    to get or set the red and blue components of color temperature.  Calling camera_set_wb_color_temp implicitly disables AWB.  color[] is an int array of length 2 where:
    • color[0] = red
    • color[1] = blue

    The return values are 0 for success, -1 for failure (fails if _array_size(color)!=2).  If you want to use these functions from the interaction window you will need to use a block to create a color[] array:

    • {int color[2]; camera_get_wb_color_temp(color); printf("Red=%d, Blue=%d\n", color[0], color[1]);}
    • {int color[]={100,200}; camera_set_wb_color_temp(color);}
  • The following are equivalent in function, but may be more convenient for interactive use:

  •  int camera_get_wb_red_temp();
     int camera_get_wb_blue_temp();
  • Use
     int camera_get_aec();
     int camera_set_aec(int enable);
    to get or set whether or not Auto Exposure Control is enabled (0=disabled, 1=enabled).
  • Use
     int camera_get_exposure();
    to get the current value of Exposure.  There is no set function for Exposure because the camera does not support that operation.
  • Use
     int camera_get_aec_ratio();
     int camera_set_aec_ratio(int val);
    to get or set the value of the Auto Exposure Ratio (AERatio) (range 1- 254, default=65).
  • Use
     int camera_get_exp_ref_level();
     int camera_set_exp_ref_level(int val);
    to get or set the value of the Exposure Reference Level (ExpRL) (range 0-224, default 160).
  • Use
     int camera_get_agc();
     int camera_set_agc(int enable);
    to get or set whether or not Auto Gain Control is enabled (0=disabled, 1=enabled).
  • Use
     int camera_get_gain();
     int camera_set_gain(int val);
    to get or set the value of Gain (range 0-248).
  •   Calling camera_set_gain also implicitly disabled AGC.

Color Model APIs

  • Color models are expressed as a range of values in the HSV (Hue, Saturation, Value) cube which are considered to be included within the range of pixels accepted by that model. 
    • Hue (range 0-359) is analogous to what we usually think of as the "color" of a pixel: Red ~= 0, Green ~= 100, Blue ~= 240. The Hue range may wrap, for example hMin=340, hMax=10 is a valid range.  However, the distance from hMax to hMin ((360 + hMax - hMin) % 360) may not exceed 120.
    • Saturation (range 0 - 223) is how pure and intense the hue is: 0 = totally unsaturated, such as black, white, or grey; 223 = totally saturated, such as neon orange, fire-engine red, etc.  Hue is most reliable, and therefore color distinction is more robust, for pixels with high Saturation.  If Saturation is too low, then the Hue calculation will be fairly random.  Therefore you can set sMin, the minimum acceptable Saturation value, but sMax is the maximum possible value of 223 for color tracking.
    • Value (range 0-223) is how dark or bright the pixel is: 0 = black, 223 = bright.  Hue is most reliable, and therefore color distinction is more robust, for pixels with high Value.  If Value is too low, then the Hue calculation will be fairly random.  Therefore you can set vMin, the minimum acceptable Value, but vMax is the maximum possible value of 223 for color tracking.
  • Use
     int color_get_model(int model_num, int model[]);
     int color_set_model(int model_num, int model[]);
    to get or set the parameters of color model model_num (range 0-2) currently in use.  model[] is an int array of length 4 where:
    • model[0] = hMin
    • model[1] = hMax
    • model[2] = sMin
    • model[3] = vMin

    The return values are 0 for success, -1 for failure (fails if _array_size(model)!=4 or arguments out of range).  If you want to use these functions from the interaction window you will need to use a block to create a model[] array:

    • {int model[4]; color_get_model(0, model); printf("H=(%d->%d), S>=%d, V>=%d\n", model[0], model[1], model[2], model[3]);}
    • {int model[]={0, 100, 200, 200}; color_set_model(0,model);}
  • The following are equivalent in function, but may be more convenient for interactive use:

  •  int color_get_ram_hmin(int model_num);
     int color_get_ram_hmax(int model_num);
     int color_get_ram_smin(int model_num);
     int color_get_ram_smax(int model_num);
     int color_get_ram_vmin(int model_num);
     int color_get_ram_vmax(int model_num);
     int color_set_ram_model(int model_num, int hmin, int hmax, int smin, int vmin);

Using the IC Simulator

1. Setting up to use the simulator
There are 3 requirements that must be fulfilled in order to use the simulator:

After these conditions are met, the simulator can be activated.

2.Opening the simulator
With the IC file you would like to simulate selected in the tab interface, hit the "simulate" button on the top toolbar. This will open the simulator window, with the current IC file loaded and ready to run.

3. Running the simulator
To start the simulator running, hit the "Execute" button at the bottom of the simulator window. This will execute whatever code is currently loaded into the simulator. To pause execution, hit the pause button. To resume it, hit the execute button again. To reset the simulator back to its starting state (similar to turning a controller board off and back on), hit the reset button. To exit the simulator and return to the IC compiler window, hit the cancel button.

4. A tour of the simulator window
The simulator provides all the inputs and outputs of the controller board it is simulating, including sensors, motors, and any board specific features.
Sensors are located in the upper left hand box. Sensor type is denoted by the letter next to the sensor number, 'a' standing for analog sensor, 'd' for digital. The values for sensors may be set by either typing in the value in the corresponding box, or using the up and down arrows to change the value. The simulator does not need to be paused in order to change the value, and the program that is currently running will react as soon as any change is made.
In addition to the usual analog and digital sensors, boards might have certain unique features such as buttons and knobs (i.e. the start/stop buttons on the Handyboard, Prgm/View on the RCX, etc...). These features are available in the box directly below the sensors, and are settable through the same methods as the sensors.
The right side of the simulator window houses the help and output features.
In the upper right hand corner is the Show Diagram button. By pressing the board diagram button, the user can bring up a picture of the controller board being simulated, in order to relate port positions to their physical positions on the actual board.
Below this is the Print Buffer display. This display is used to show what would usually be on the screen of the controller board, and is customized to show the text in the same format as it will be shown on the controller board.
Finally, the motor output values are displayed below the Print Buffer window. These reflect the PWM settings of the motors available on the board.

5. The simulator interaction and global windows
The simulator has an interaction feature, similar to using a real controller board. Users may type commands into the interaction window and it will return the results from the current state of the simulated board. In addition, there is now a global tracking window. This displays the names, types, addresses, and values of globals in the currently loaded program, and updates their values as they change during the course of the program's execution.

6. iROBOsim
When using the XBC or XBC+Create you can insert into any program the command iROBOinit(<world>) where world can be EMPTYWORLD, RULERWORLD, ARENAWORLD, BIGEMPTYWORLD, or BIGWORLD.
This is a noop to code loaded onto the XBC, however if the code is loaded into the simulator it will open up a graphic window and display a robot similar to the Create. With the XBC+Create target all of the Create motion commands may be used along with the bump sensors (gc_lbump and gc_rbump), distance and angle sensors. Other commands are simply noops in the simulator. For the XBC target motors 0 and 1 are used for the drive wheels and digital sensors 15 and 8 are used for the left and right front bumpers. Both targets use digitals 9 & 14 for the right and left rear bumpers.