Upload
akshay-punde
View
235
Download
0
Embed Size (px)
Citation preview
7/27/2019 Interactive c Robot Manual En
1/120
1
omponents used in building a small automatic robot Robo-11
68HC11 Micro-controller Activity BoardIt comes with a CX-4 cable to downloadthe program. This board is used to controlthe operation of the robot. It has a 32KBmemory, 21 analog input channels, 9digital inputs, 9 digital outputs, and itdrives 4 DC motors and 6 RC servo motors.
Universal PlatePlate size is 160 x 60 mm. Thereare 341 3-mm size holes with adistance of 5 mm between eachhole. Two plates are provided.
Motor GearboxUses a 6-9 V and 180 mA DCmotor with a ratio of 48:1;torque 4kgF/cm; Two sets areprovided.
TrackThere are 3 sizes. Four 8-Joint
tracks; Four 10-Joint Tracks;and two 30-joint tracks.
Angled Shaft BaseTwo pieces of each the long baseand short base are provided.
Metal Axel4 mm in diameter and 100 mmin length. Four axels come in the
set.
7/27/2019 Interactive c Robot Manual En
2/120
2
WheelsThere are four different types which are MainTrack Wheel (2 Pieces), Large Track Support
Wheel (2 pieces), Small Track Support Wheel (10pieces), and hubs (12 pieces).
Knobby PlateThis is used to attach the AX-11 with the universalplates.
Angled Joiner20 pieces of varied color joiners made from PVCplastic. They can be connected together or byusing screws and 3 mm nuts in installation.
Obtuse Joiner20 pieces of varied color 135 degree obtuseoiners made from PVC plastic. They can beconnected together or by using screws and 3 mmnuts in installation.
Strength Joiner20 pieces of varied color joiners made from PVCplastic. They can be connected together or byusing screws and 3 mm nuts in installation.
Nut and Screw SetThere are two 2 mm open-end screws, four 3 x 6mm screws, thirty 3x10 mm screws, four 3 x 15mm screws, four 3 x 25 mm screws, and thirty 3mm nuts.
Switch InputThe switch input is used to detect collision at logic
0. Two sets along with the connecting cable areprovided.
IR ReflectorUsed to detect the perimeter, lines, and the wheelcode. The results are in voltage. Three sets alongwith the connecting cable are provided.
IR RangerMeasures distance ranging from 4 to 30 cm using
infrared light. The results are in voltage.
7/27/2019 Interactive c Robot Manual En
3/120
3
Start by putting together the two track wheels,which each wheel using one 30-joint track, one10-joint track, and two 8-joint track. Connect alltracks together to form one track wheel that issuitable for the size of the robot.
1
Attach the motor gearbox sets to the universalplate using a 3 x 6 mm and 3 x 10 mm screw.Position the Motor Gearbox sets as shown in thepicture below.
2
BUILDING THE ROBOT
7/27/2019 Interactive c Robot Manual En
4/120
4
Take the long angled shaft base and attach it to the universalplate. In between the plate and the long angled shaft, place thestrength joiner. Screw them all in together using a 3 x 10 mmscrew and nut, positioning it at the 8th hole from the side wherethe motor was attached. The smooth side of the shaft baseshould be turned outwards as shown in the picture. Tighten thescrew and nut.
3
Flat plastic joiner
Turn the universal plate over to the side where the motors areattached. Attach the short angled shaft base at the end of theplate as shown in the picture.
4
Use a 3 x 10 mm screw and nut to attachthe short angled shaft base to theuniversal plate
7/27/2019 Interactive c Robot Manual En
5/120
5
Turn the plate bottom up and insert the metal axel into the holes
of the long angled shaft in the positions of 1, 4, and 7 (Countingfrom the side with the installed motor).5
Place the small track supportwheels over the metal axelwith the front of the wheelsturned outwards. Insert thehubs over the wheels and useyour fingers to press intightly. Insert a metal axelinto the two short angledshaft bases. Then insert thelarge track support wheelsand hub to it.
6
7/27/2019 Interactive c Robot Manual En
6/120
6
Attach the main track wheels to the motor axels with the 2 mmopen-end screws.7
Attach an angled joiner to the universal plate between the twomotor gearboxes with a 3 x 10 mm screw and a 3 mm nut. Thenattach two more at the Large track support wheels, which is
opposite from the motors as shown in the picture.
8
7/27/2019 Interactive c Robot Manual En
7/120
7
Take 3 more angled joiners and attach them to the other
universal plate as shown in the picture. The position of theangled joiners must be the same as the ones attached to theplate with the motor gearboxes in Step 8.
9
Insert a strength joiner into all 3 angled joiners to create asupport base for the plate with the motor gearbox sets. Thenplace the two universal plates together. This will make it easier toremove the robot structure for any internal modifications thatmay be needed.
10
7/27/2019 Interactive c Robot Manual En
8/120
8
Then take the track wheels that were put together in step 1 andplace it over the supporting wheels on both sides of the robot.Make sure that both wheels are aligned with one another.
11
Place the knobby plate with the
two-sided glue onto the top ofthe finished robot. Remove thesticker and place the AX-11board onto the glue surface. Thiswill make it easier to remove orshift the AX-11 board. Thenconnect the signal cable of theleft motor to exterior terminal M-0 and the signal cable of theright motor to the interior
terminal M-1.
12
7/27/2019 Interactive c Robot Manual En
9/120
9
Preparing to Download the Program
Preliminary Preparations in Using Interactive Cwith the AX-11 board on the Robo-11 robot.
The preparations that we are about to talkabout is writing the main control program, or whatthey call the Firmware, into the memory of theAX-11 board. This will be done only once in thebeginning, or if the main program data disappears,or if the AX-11 board is unable to receive datafrom the operational program written by theprogrammer.
Turn on the POWER switch on the AX-11 board. If the voltage ofthe battery on the AX-11 is enough, the green PWR LED will be litbrightly. If not, the LED will be dimly displayed and the red BATTLED will indicate that the voltage level is low, as shown in FigureA1-1. Use the +12V DC Adaptor that came with the AX-11 boardas the power supply instead by connecting it to the outlet on the
board. Once power is supplied, the yellow CHARGE LED will light,and the red LED will disappear as shown in Figure A1-2.
1
7/27/2019 Interactive c Robot Manual En
10/120
10
Take the AX-11 and connect it to the serial port of the computeras shown in Figure A1-3. The green SER LED will light, indicatingthat the connection of the AX-11 to the serial port of the
computer was successful, and is ready for use.
2
7/27/2019 Interactive c Robot Manual En
11/120
11
Problem Solving if the computer
has only one USB port
Use a USB port to analog port RS-232converter, in which we recommend theUCON-232 board. (www.inex.co.th)
Open the Interactive C program
by going into Start Program Interactive C 4.30ax Interactive
C for AX-11. A title window willappear for an instant beforechanging to the Select ControllerType window. Choose AX-11.
3
The Port Selection window willappear for you to choose theserial port of the computer that isto be used to communicate withthe AX-11 board. Choose the portyou want and click Connect now.
4
Go to the menu Tools Download
firmware. A window will appear tochoose the serial port ofcommunication again. Once youhave chosen, click DownloadFirmware.
5
http://www.inex.co.th%29/http://www.inex.co.th%29/7/27/2019 Interactive c Robot Manual En
12/120
7/27/2019 Interactive c Robot Manual En
13/120
13
If everything is alright, awindow displaying theFirmware download status will
appear. Once the download isdone, a beep will be heardfrom the AX-11 board, and thestatus window of theInteractive C program willdisplay the messageDownload Successful. Thedisplay of the AX-11 will showIC 4.30 on AX-11 ActivityBoard, ending with a blinkingheart. The Interactive Cprogram will then go to theInteraction window, which isused for testing the program.
The Robo-11 is now ready forprogram coding and operation.
8
Testing the Interactive C Program
After downloading the main controlprogram, or the firmware, the next stepis to write a basic function to test theoperation of the AX-11.
1Go to the Interaction window,type in the function
Printf (Hello world !\n);
Then press Enter.
2 The monitor shows the resultsfrom the AX-11, displayingHello world! on the topsentence. The display of theInteraction window will displaythe message
This means that the AX-11 boardcan now interact with theInteractive C program.
7/27/2019 Interactive c Robot Manual En
14/120
14
Next we will create a simple Interactive C program to use with the AX-11 board.
1 Click New to create a newprogram folder
2 Type in the program below, and
save it as hello.ic
3 Click Download to download theprogram. A window will appearasking to save the file *.ic first.
Here, the file is hello.ic. Awindow displaying the status ofthe download will then appear.
4 Run the program by
Method 1: Turn off and on thePOWER switch once to reset theAX-11 board.Method 2: Run the program byclicking Run Main on theInteractive C window. Thenchoose the Interaction window,the message below will appear
The message Hello world!
will appear on the top of theAX-11 display screen.
7/27/2019 Interactive c Robot Manual En
15/120
15
Things to be know when downloading the program to the AX-11
If the AX-11 and Interactive C program is used together continuously withoutturning off the program, the programmer would be able to download and test theprogram anytime, even when the POWER switch is turned off. This is because theprogram is stored in a non-volatile system memory.
If the Interactive C program is closed and reopenedagain while the AX-11 board is still on, and the firmwarestill operating, the communication between the AX-11and the Interactive C program must be reestablished.
Choose the serial port used to communicate, and thenclick Connect Now. A window displaying the status ofdownloading the Interactive C library to the AX-11 boardwill appear as seen in the picture.
Then we will go to the Interaction window, causing the program that was saved inthe memory previously to have disappeared; therefore it must be downloadedagain.
This means that every time the Interactive C program is closed and openedagain, the user must always download the program he needs into the memoryagain. This is because the Interactive C program is a program that needs to beconnected to the hardware in order to check its status continuously. Therefore, ifthe communication is lost because it was turned off, the communication mustalways be reestablished at the beginning by downloading the programs library tothe AX-11 board.
The AX-11 Power Supply
The AX-11 uses 8 serial Nickelmethus-hydridebatteries size AA with a voltage of 1.2V 1700mAHor above, therefore resulting in a supply of at least9.6 1700 mAH. The recommended time incharging the batteries is at least 10 to 15 hours.Low current is used to charge the batteries inorder to extend the battery life.
If the AX-11 board is fully charged, it can beused continuously for 2-4 hours, depending on the
number of peripherals connected and the amountof voltage they use.
7/27/2019 Interactive c Robot Manual En
16/120
7/27/2019 Interactive c Robot Manual En
17/120
17
/* Example for Robot basic movementHardware configuration
- Motor left connected to DC Motor chanel M-0- Motor right connected to DC Motor chanel M-1 */
#define pow 50 /* Configuration power drive motor */
void main()
{ao(); // All off motor every channelprintf(Press Start!\n); // Display message on LCDstart_press(); // Wait until Press start key
while(1) // Infinite loop{run_fd(2.0); // Robot forward 2 sec
run_bk(2.0); // Robot backward 2 sec}}void turn_left(float spin_time)
{motor(0,-pow); // Motor0 backward for pow define valuemotor(1,pow); // Motor1 forward for pow define valuesleep(spin_time); // Delay set by parameter spin_time
}void turn_right(float spin_time){motor(0,pow); // Motor0 forward for pow define valuemotor(1,-pow); // Motor1 backward for pow define valuesleep(spin_time); // Delay set by parameter spin_time}
void run_fd(float delay){motor(0,pow); // Motor0 forward for pow define valuemotor(1,pow); // Motor1 forward for pow define value
sleep(delay); // Delay set by parameter delay}void run_bk(float delay)
{motor(0,-pow); // Motor0 backward for pow define valuemotor(1,-pow); // Motor1 backward for pow define value
sleep(delay); // Delay set by parameter delay}
ROBO-11 Testing
After the Robo-11 has been put together, we will next write a program to test thefunctioning of the motor to see whether it is working together properly and if it isready for its future operations or not. A simple program will be downloaded for therobot to move forward 2 seconds, move backwards 2 seconds, and continue to repeatthese steps.
T e in the followin ro ram code and download it to the Robo-11
7/27/2019 Interactive c Robot Manual En
18/120
18
/* Example for Robot movement, program to near square movementHardware configuration- Motor left connected to DC Motor chanel M-0- Motor right connected to DC Motor chanel M-1 */
#define pow 40 /*Configuration power drive motor*/
void main()
{ao(); // All off motor every channelprintf(Press Start!\n); // Display message on LCDstart_press(); // Wait until Press start key
while(1) // Infinite loop{run_fd(2.0); // Robot forward 2 secturn_left(1.0); // Robot backward 1 sec}
}
Testing It
Place the Robo-11 on the floor and then turn on the POWER switch. The LCDscreen displays the message Press Start. Press START on the AX-11.
The robot will move forward for 2 seconds, using only 50% of its power. Observethe motor LED on the AX-11 board. Both must be green. Then the robot will movebackwards for 2 seconds. Observe the motor LED on the AX-11 that shows thefunctionality of the motors. Both will turn to red.
If you dont get these results, switch the motor cables terminal
charge on the AX-11 until you get the correct results. Use this motorconnection for future operations.
Robo-11 Test (2)
From Test (1), the next step would be to include additional conditionsfor the robot so that the robot can move in the direction or waydesired. In this test, the Robo-11 is told to move in a square-likeshape.
Type in the following program code and download it to the Robo-11
7/27/2019 Interactive c Robot Manual En
19/120
19
void turn_left(float spin_time)
{motor(0,-pow); // Motor0 backward for pow define valuemotor(1,pow); // Motor1 forward for pow define valuesleep(spin_time); // Delay set by parameter spin_time}void turn_right(float spin_time)
{motor(0,pow); // Motor0 forward for pow define valuemotor(1,-pow); // Motor1 backward for pow define valuesleep(spin_time); // Delay set by parameter spin_time}void run_fd(float delay)
{motor(0,pow); // Motor0 forward for pow define value
motor(1,pow); // Motor1 forward for pow define valuesleep(delay); // Delay set by parameter delay}
void run_bk(float delay){motor(0,-pow); // Motor0 backward for pow define valuemotor(1,-pow); // Motor1 backward for pow define value
sleep(delay); // Delay set by parameter delay}
Testing It
Place the Robo-11 on the floor and then turn on the POWERswitch. The LCD screen displays the message Press Start.Press START on the AX-11. The robot will move forward for 2seconds, using only 50% of its power. Then the robot willturn left for 2 seconds and continue doing so. It can beobserved that the robot is moving in a square-like
movement.
How much the Robo-11 Standard is able to move in a perfectsquare depends on many factors, such as the current batterylevel, the current supplied to the motor, movement time,and the friction at the wheels of the robot.
7/27/2019 Interactive c Robot Manual En
20/120
20
1.If the downloaded program does not work.Solve by
Check the download cable by checking if the SER LED is green. Check the power supply by checking if the BATT LED is red. If it is
lighted bright it means that the battery is low. Use the external powerfrom the DC adapter +12V 500 mA
Download the firmware again.
2.If the AX-11 cannot communicate with theInteractive C program.
Solve by Check the power supplied to the AX-11 by checking if the PWR LED is
green.
Check the download cable by checking if the SER LED is green. Check the power supply by checking if the BATT LED is red. If it is
lighted bright it means that the battery is low. Use the external powerfrom the DC adapter +12V 500 mA
If everything is ok, download the firmware again.
3.If the firmware can not be downloadedSolve by
Check the power supplied to the AX-11 by checking if the PWR LED isgreen. Check the download cable by checking if the SER LED is green. Check the power supply by checking if the BATT LED is red. If it is
lighted bright it means that the battery is low. Use the external powerfrom the DC adapter +12V 500 mA
If it is still not working, send the robot back to the manufacturer ordistributor to check its functionality
Basic Problem Solving
7/27/2019 Interactive c Robot Manual En
21/120
21
IC 4 Programmers Manual
IntroductionInteractive C (IC for short) is a C language consisting of a compiler (with interactivecommand-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 thancompiling 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:
Interpreted execution that allows run-time error checking. For example, IC does arraybounds checking at run-time to protect against some programming errors.
Ease of design. Writing a compiler for a stack machine is significantly easier thanwriting one for a typical processor. Since IC's p-code is machine-independent,
porting IC to another processor entails rewriting the p-code interpreter, rather than
changing the compiler.
Small object code. Stack machine code tends to be smaller than a native coderepresentation.
Multi-tasking. Because the pseudo-code is fully stack-based, a process's state isdefined solely by its stack and its program counter. It is thus easy to task-switch simplyby loading a new stack pointer and program counter. This task-switching is handled
by the run-time module, not by the compiler.
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 4 was written by Randy Sargent of the KISS Institute for Practical Robotics. Randy
was assisted by Mark Sherman. Portions of the code and the libraries are based on
the public distribution of IC 2.8 written by Randy Sargent, Anne Wright and Fred
Martin.
7/27/2019 Interactive c Robot Manual En
22/120
22
Using IC
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 thecommand 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 consolecomputer 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 curlybrace { 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);}
7/27/2019 Interactive c Robot Manual En
23/120
23
IC Interface
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 theinterface is always the interaction window.
The File button has standard entries forNew, Open, Close, Save, Save As, Print, and Exit.UnderFile - 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 besaved, 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-codeinterpreter, 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 tothe display, and for setting up the serial interface to a board.
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.
7/27/2019 Interactive c Robot Manual En
24/120
24
The main() Function
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 directlyfrom 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, whenhooking the board back to the computer), hold down the board's Start button while
activating the board. The board will then reset without running main().
IC versus Standard C
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. Forinstance, 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. Forinstance, 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 andstandard 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.
7/27/2019 Interactive c Robot Manual En
25/120
25
A Quick C Tutorial
Most C programs consist of function definitions and data structures. Here is a simple Cprogram that defines a single function, called main.
/* Simple example
IC Programmer's Manual
*/
void main(){
printf("Hello, world!\n"); // Something simple
}
The expression/* */
forms a multi-line orbracketed comment. In contrast, text that starts with "//" forms asingle
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, thenull 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 anempty 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. Ourdemonstration 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.
7/27/2019 Interactive c Robot Manual En
26/120
26
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 codedefines the functionsquare, 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 forsquare is contained within the set of curly braces. In fact, it consists of a singlestatement: 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)));
return(h);
}
7/27/2019 Interactive c Robot Manual En
27/120
27
This code demonstrates several more features of C. First, notice that the floating pointvariable h is defined at the beginning of the hypotenuse function. In general, whenever anew 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-inIC 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 bypreceding 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
Variables and constants are the basic data objects in a C program. Declarations list thevariables to be used, state what type they are, and may set their initial value.
7/27/2019 Interactive c Robot Manual En
28/120
28
Variables
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 notbe used as variable names.
Functions and global variables may not have the same name. In addition, if a localvariable 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
In C, variables can be declared at the top level (outside of any curly braces) or atthe start of each block (a functional unit of code surrounded by curly braces). In
general, a variable declaration is of the form:
; or
=;
In IC, can be int, long, float, char, or struct, and determinesthe primary type of the variable declared. This form changes somewhat whendealing 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
If a variable is declared within a function, or as an argument to a function, its bindingis 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.
7/27/2019 Interactive c Robot Manual En
29/120
7/27/2019 Interactive c Robot Manual En
30/120
30
Persistent Global Variables
A special persistent form of global variable, has been implemented for IC. Apersistent global variable may be initialized just like any other global variable, but itsvalue 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 keywordpersistent. 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 mainis 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 ICsession 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 isturned on and off.
7/27/2019 Interactive c Robot Manual En
31/120
31
ConstantsInteger Constants
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 usefulbinary format using the "0b" prefix (e.g., 0b1001001). Octal constants using the zero
prefix are not supported.
Long Integer Constants
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
Floating point numbers may use exponential notation (e.g., "10e3" or "10E3") or maycontain 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
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
The special constant NULL has the value of zero and can be assigned to andcompared 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 itsvalue 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.
7/27/2019 Interactive c Robot Manual En
32/120
32
Data Types
IC supports the following data types:
16-bit Integers
16-bit integers are signified by the type indicator int. They are signed integers, andmay be valued from -32,768 to +32,767 decimal.
32-bit Integers
32-bit integers are signified by the type indicatorlong. They are signed integers, and
may be valued from -2,147,483,648 to +2,147,483,647 decimal.
32-bit Floating Point Numbers
Floating point numbers are signified by the type indicator float. They haveapproximately seven decimal digits of precision and are valued from about 10^-38
to 10^38.
8-bit Characters
Characters are an 8-bit number signified by the type indicatorchar. A character'svalue typically represents a printable symbol using the standard ASCII charactercode, but this is not necessary; characters can be used to refer to arbitrary 8-bit
numbers.
Pointers
IC pointers are 16-bit numbers which represent locations in memory. Values inmemory can be manipulated by calculating, passing and dereferencing pointers
representing the location where the information is stored.
Arrays
Arrays are used to store homogenous lists of data (meaning that all the elements ofan 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.
7/27/2019 Interactive c Robot Manual En
33/120
33
Structures
Structures are used to store non-homogenous but related sets of data. Elements of astructure 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 thenumber of arguments passed to functions, increasing the effective number of valueswhich can be returned by functions, and creating complex data representations
such as directed graphs and linked lists.
Pointers
The address where a value is stored in memory is known as the pointer to that value. It isoften 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 computingenvironments that you are probably used to return helpful messages like 'SegmentationViolation' 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 likelyto go undetected, and will likely render invalid your data, your program, or even the
pcode interpreter.
Pointer Safety
In past versions of IC, you could not return pointers from functions or have arrays ofpointers. In order to facilitate the use of structures, these features have been added to thecurrent 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 specialzero 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.
7/27/2019 Interactive c Robot Manual En
34/120
34
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 functionterminates the space where its values were being stored is recycled. Therefore not only
may dereferencing such pointers return incorrect values, but assigning to those addressescould lead to serious data corruption. A good way to prevent this is to never return theaddress 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, orstruct). 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
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 * operatorbefore 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, arrayelement, or structure element reference.
There are two main differences between how you would use a variable of a given typeand a variable declared as a pointer to that type.
For the following explanation, considerX and Xptr as defined as follows:
7/27/2019 Interactive c Robot Manual En
35/120
35
long X; long *Xptr;
Space Allocation -- Declaring an object of a given type, as X is of type long,
allocates the space needed to store that value. Because an IC long takes four bytesof memory, four bytes are reserved for the value of X to occupy. However, a pointerlike Xptr does not have the same amount of space allocated for it that is needed for
an object of the type it points to. Therefore it can only safely refer to space whichhas already been allocated for globals (in a special section of memory reserved for
globals) or locals (temporary storage on the stack).
Initial Value -- It is always safe to refer to a non-pointer type, even if it hasn't beeninitialized. However pointers have to be specifically assigned to the address of legallyallocated space or to the value of an already initialized pointer before they are safe
to use.
So, for example, consider what would happen if the first two statements after X and Xptrwere 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 bevalid 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 ArgumentsPointers 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 isgiven to the function that is being called. This is in contrast to call-by-value, the standardway that functions are called, in which the value of a variable is given the to function
being called.
7/27/2019 Interactive c Robot Manual En
36/120
36
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 inthe 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 answersum/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 FunctionsPointers 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 pointerdeclaration.
int right,left; int *dirptr(int dir)
{ if (dir==0) {
return(&right);
} if (dir==1) {
return(&left);
} return(NULL);
}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.
7/27/2019 Interactive c Robot Manual En
37/120
37
Arrays
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 anumber 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, sendan 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. Thisincompatibility is caused by the fact that references to IC arrays are checked to insure thatthe reference is truly within the bounds of that array. In order to accomplish this checking inthe 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 sametype are incompatible types in IC, whereas they are largely interchangeable in regular C.
Declaring and Initializing Arrays
Arrays are declared using square brackets. The following statement declares an array often integers:
int foo[10];
In this array, elements are numbered from 0 to 9. Elements are accessed by enclosing theindex 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 atdeclaration by specifying the array elements, separated by commas, within curly braces. Ifno 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,
7/27/2019 Interactive c Robot Manual En
38/120
38
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 maynot exceed the specified length of the array or an error results. If, on the other hand, youspecify 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:
charstring[]= "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 (forexample). Character arrays can be initialized using the curly braces syntax, but they willnot be automatically null-terminated in that case. In general, printing of character arrays
that are not null-terminated will cause problems.
Passing Arrays as ArgumentsWhen an array is passed to a function as an argument, the array's pointer is actuallypassed, 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 apointer 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 arrayelement 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 anarray of integers.
7/27/2019 Interactive c Robot Manual En
39/120
39
When passing an array variable to a function, you are actually passing the value of thearray 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
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 thesecond set of brackets is the length of each of the 1-D arrays of int. In this example, kis 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 thisexample by adding more brackets in the declaration.
Determining the size of Arrays at Runtime
An advantage of the way IC deals with arrays is that you can determine the size of arraysat runtime. This allows you to do size checking on an array if you are uncertain of itsdimensions and possibly prevent your program from crashing.
Since_array_size is not a standard C feature, code written using this primitive will only beable to be compiled with IC.
The_array_size primitive returns the size of the array given to it regardless of the dimensionor type of the array. Here is an example of declarations and interaction with the
_array_size primitive:
7/27/2019 Interactive c Robot Manual En
40/120
40
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 */
Structures
Structures are used to store non-homogenous but related sets of data. Elements of astructure 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 whichcan 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 structuretype, and access its elements.
struct foo{
int i;
int j;};
struct foo f1; void set_f1(int i,int j)
{
f1.i=i;f1.j=j;
} void get_f1(int *i,int *j)
{
*i=f1.i;*j=f1.j;
}
7/27/2019 Interactive c Robot Manual En
41/120
41
The first part is the structure definition. It consists of the keyword struct, followed by thename of the structure (which can be any valid identifier), followed by a list of namedelements 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 structfoo just like any other type. Theline
struct foo f1;is a global variable declaration which declares the variable f1 to be of type structfoo.
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 structurepointed to.
struct foo *fptr;
void main(){
fptr=&f1;fptr->i=10;
fptr->j=20;
}In this example, fptr is declared to be a pointer to type structfoo. In main, it is set to point to
the global f1 defined above. Then the elements of the structure pointed to by fptr (in thiscase these are the same as the elements of f1), are set. The arrow operator is used insteadof 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 orreturned from functions.
7/27/2019 Interactive c Robot Manual En
42/120
42
Complex Initialization examples
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 asuitable 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 lengthis 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} };
charc[]="Hi there how are you?"; charcarr[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 typestruct bar with i=5 and j=10 */
charlc[]=carr[2]; /* local string lc withinitial value "how" */
...
}
7/27/2019 Interactive c Robot Manual En
43/120
43
Statements and ExpressionsOperators 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 areexpressions, assignments, function calls, or control flow statements which make up C
programs.
OperatorsEach of the data types has its own set of operators that determine which operations may
be performed on them.
Integer Operations
The following operations are supported on integers:
Arithmetic. addition +, subtraction -, multiplication *, division /.
Comparison. greater-than >, less-than =, less-than-equal
7/27/2019 Interactive c Robot Manual En
44/120
44
Floating Point Numbers
IC uses a package of public-domain floating point routines distributed by Motorola. Thispackage includes arithmetic, trigonometric, and logarithmic functions. Since floating pointoperations 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 =, less-than-equal & ^ |
7/27/2019 Interactive c Robot Manual En
45/120
7/27/2019 Interactive c Robot Manual En
46/120
46
Precedence and Order of Evaluation The following table summarizes the rules forprecedence 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
! ~ ++ -- - () 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
7/27/2019 Interactive c Robot Manual En
47/120
47
Control Flow
IC supports most of the standard C control structures. One notable exception is the switch
statement, which is not supported.
7/27/2019 Interactive c Robot Manual En
48/120
48
Statements and Blocks
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
The if else statement is used to make decisions. The syntax is:
if ()
else
is evaluated; if it is not equal to zero (e.g., logic true), then isexecuted.
The else clause is optional. If the if part of the statement did not execute, and the else ispresent, then executes.
While
The syntax of a while loop is the following:
while ()
while begins by evaluating . If it is false, then is skipped. If it is true,then is evaluated. Then the expression is evaluated again, and the same
check is performed. The loop exits when becomes zero.
One can easily create an infinite loop in C using the while statement:
while (1)
For
The syntax of a forloop is the following:
for(;;)
The forconstruct is equivalent to the following construct using while:;
while ()
{
;
}
7/27/2019 Interactive c Robot Manual En
49/120
49
Typically, is an assignment, is a relational expression, and is anincrement or decrement of some manner. For example, the following code counts from 0to 99, printing each number along the way:
int i; for(i = 0; i < 100; i++)
printf("%d\n", i);
Break
Use of the breakstatement provides an early exit from a while or a forloop.
7/27/2019 Interactive c Robot Manual En
50/120
50
LCD Screen Printing
IC has a version of the C function printf for formatted printing to the LCD screen.
The syntax of printf is the following:
printf(, , ... , );
This is best illustrated by some examples.
Printing Examples
Example 1: Printing a message
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 theend 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
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
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.
7/27/2019 Interactive c Robot Manual En
51/120
51
Example 4: Printing a floating point number
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
printf("A=%x B=%x\n", a, b);
The form %x formats an integer to print in hexadecimal.
Formatting Command Summary
Format CommandData TypeDescription
%d
int
decimal number
%xint
hexadecimal number
%b
int
low byte as binary number
%cint
low byte as ASCII character
%ffloatfloating point number
%schararray
char array (string)
7/27/2019 Interactive c Robot Manual En
52/120
52
Special Notes
The final character position of the LCD screen is used as a system "heartbeat." This
character continuously blinks between a large and small heart when the board isoperating properly. If the character stops blinking, the board has failed.
Characters that would be printed beyond the final character position are truncated.
When using a two-line display, the printf() command treats the display as a singlelonger line.
Printing of long integers is not presently supported.
7/27/2019 Interactive c Robot Manual En
53/120
53
Preprocessor
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. Usingpreprocessor 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, forinstance, for debugging purposes.
The special preprocessor command #use has been included to allow programs to cause aprogram 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()
{
chars[32] = "text string wrapping badly\n";fix (s); /* apply my fix function to s and print it */
printf(s);}
Preprocessor Macros
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 todefine 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(){
GO(0,0);
}
7/27/2019 Interactive c Robot Manual En
54/120
54
Preprocessor macro definitions start with the #define directive at the start of a line, andcontinue to the end of the line. After #define is the name of the macro, such asRIGHT_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_LEFTmacros 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, theneach place the argument appears in the body is replaced with the actual argument
provided.
Invocations of macros without arguments look like global variable references. Invocationsof 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 beforethey are called, whereas macros simply perform text replacement. For example, if theactual 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 constantsto 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.
7/27/2019 Interactive c Robot Manual En
55/120
55
Conditional compilation
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. TheIC preprocessor provides a convenient way of doing this by using the #ifdef directive.
void go_left(int power){
GO_LEFT(power); #ifdef DEBUG printf("Going Left\n");
beep(); #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 macrodefinition occurs inside an #ifdef block, it will be defined regardless of whether the #ifdefevaluates 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 thisdocument. Refer to a C reference manual for how to use them.
7/27/2019 Interactive c Robot Manual En
56/120
56
Comparison with regular C preprocessors
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 compiledcompletely 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 externglobal 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 inanother 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, externdeclarations, and macros in header files which are then included at the top of each C fileusing 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 apreprocessor with file scope. Therefore, for consistency it was desirable to give IC macros
the same behavior as globals and functions. Therefore, preprocessor macros have globalscope. 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 ofwhether 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 Cpreprocessors.
7/27/2019 Interactive c Robot Manual En
57/120
57
The IC Library File
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 isbeing used, a different library file will be required. IC may be configured to load differentlibrary 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 andRCX; 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, commonly a description of commonly used library functions follows.
7/27/2019 Interactive c Robot Manual En
58/120
7/27/2019 Interactive c Robot Manual En
59/120
59
fd(); /* turns on the motor specified (direction is determined by plug
orientation */
bk();
/* turns on the motor specified in the opposite direction from fd */
off();
/* turns off the motor specified */
ao();
/* turns all motor ports off*/Processes
Processes work in parallel. Each process, once it is started, will continue until it finishes oruntil it is killed by another process using the kill_process(); statement. Each
process that is active gets 50ms of processing time. Then the process is paused temporarilyand 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. ProcessIDs 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((, , . . .)); /*start_process returns an integer that is the
and starts the function as a separate
process */
defer();
/* when placed in a function that is used as a process thiswill cause that process to give up the remainder of its time
slice whenever defer is called */
kill_process(); /* this will terminate the process specified by the
*/
7/27/2019 Interactive c Robot Manual En
60/120
60
Encoders (Handy Board only)
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 forsensors connected to (digital) ports 7,8,12,13. The corresponding values are0,1,2,3. Every enabled encoder uses a lot of the HB's processor -- so don't enable an
encoder unless you are going to use it, and never put an enable statement inside of a
loop.
enable_encoder(); /* turns on the specified encoder (either 0,1,2, or 3 which are
plugged into digital ports 7, 8, 12, 13 respectively). This
should be done only once - never enable an already enabled
encoder. If an encoder is not enabled, read_encoder will
always return 0. */
disable_encoder() /* turns off the specified encoder*/
reset_encoder()
/*sets the specified encoder value to 0 */
read_encoder()
/*returns an int that is the current value of the specified
encoder*/
7/27/2019 Interactive c Robot Manual En
61/120
61
Controlling the DC Motors
To Control the DC Motors, Please ensure that the moors are connected to the MIII Main
board before programming.
Procedure
- Connect the DC Motors to M-0 and M-1 channel on the Main Board.- Make sure the Interactive C Program is opened. Select a NEW Program or continue
with your existing Program.- The Following Sample Code, DC-CODE, shows how you can control the DC Motors.- After you have typed / inserted the code, click on the RUN MAIN button.
- Observe the Motor Indicator on the LCD Screen.
RESULTS
Observe and you will see the following:
- GREEN LED Lights Up.- Motor Turns in 1 direction for 2 Seconds
- RED LED Lights Up
- Motor Turns in faster by 30% in another direction for 2 Seconds- This Operation continues in an endless loop
7/27/2019 Interactive c Robot Manual En
62/120
62
DC-CODE
IMPORTANT COMMANDS
While ( ) {.} A represents loops, 1 = INFINITE LOOPS.. represents the code inside
Motor ( , ); B represents the board motor numberC represents the % of power
Sleep ( ); D represents the number of seconds to wait.D
CB
A
void main(){
while(1) // Infinite loop{
motor(0,50); // Motor0 forward at 50% of maximum power
motor(1,50); // Motor1 forward at 50% of maximum power sleep(2.0); // Delay 2 sec
motor(0,-80); // Motor0 backward at 80% of maximum power motor(1,-80); // Motor1 backward at 80% of maximum power
sleep(2.0); // Delay 2 sec }
}
/* Example for drive motor *//*
Hardware configuration
- Motor left connected to DC Motor channel M-0- Motor right connected to DC Motor channel M-1
*/
COMMENTS
MAIN PROG
7/27/2019 Interactive c Robot Manual En
63/120
63
Controlling RC-Servo Motors
The Set of servo motors provided in
the package can also beprogrammed to be run with the main
board. The main boards capabilitycan allow up to 6 servo motors.
In Interactive C, we can use 2commands. They are
init_expbd_servos( );A represents ON or OFF 1 for ON, 0 for OFF
servo = ; B represents the board servo number, from 0to 5.C represents the Servo DRIVE VALUE (Power ).
Procedure
- Connect the RC Servo motor to Channel 0 on the main board.
- BE CAREFUL OF THE COLOR CODE.
- WHITE GOES TO S- RED to +
- BLACK to - Make sure the Interactive C Program is opened. Select a NEW Program or continue
with your existing Program.
- The Following Sample Code, SERVO-CODE, shows how you can control the ServoMotors.
- After you have typed / inserted the code, click on the RUN MAIN button.- Observe the Servo Motors Operations.
CB
A
7/27/2019 Interactive c Robot Manual En
64/120
64
SERVO CODE
IMPORTANT COMMANDS
Init_expbd_servos ( );A represents either 1 or 0. 1 is to turn servo motors ON. 0 is to OFF servo motors.
servo = ;B represents the Servo Channel.C represents the Drive Value ( POWER ).
CB
A
void main(){
int i=600; // Declare and define servo drive value
init_expbd_servos(1); // Enable servo motor driver
while(!stop_button()) // Check STOP switch pressed{
servo0 = i; // Drive servo motor ch-0 with servo drive value sleep(1.0); // Delay 1 sec
i+=100; // Increase value step = 100if(i>4200) // Check angle>180 deg
{
i=600; // Set to origin}
}
init_expbd_servos(1); // Disable servo motor driver
/* Servo motor test*/
/*
Hardware configuration
- servo motor connected to ch-0
*/
COMMENTS
MAIN PROG
7/27/2019 Interactive c Robot Manual En
65/120
65
Controlling the SWITCH Sensor
The Main Board allows expandability of up to 9 DIGITAL Inputs.
Procedure
- Connect the Switch sensor to DI-5 ( Digital Input 5) on the Main Board.- Make sure the Interactive C Program is opened. Select a NEW Program or continue
with your existing Program.- The Following Sample Code, SWITCH-CODE- After you have typed / inserted the code, click on the RUN MAIN button.
- Observe the LCD Screen on the Main Board.
7/27/2019 Interactive c Robot Manual En
66/120
7/27/2019 Interactive c Robot Manual En
67/120
7/27/2019 Interactive c Robot Manual En
68/120
68
LIGHT CODE
IMPORTANT CODES
=analog( );A Represents Value of Analog Input.B Represents Channel / Port number.
BA
void main()
{int value; // Declare keep input from touch sensor //
{
value = analog(31); // Keep value from AI-31 channelprintf("Light %d\n",value); // Display Reflect value
sleep(0.1); // Delay 0.1 sec for display }}
/*Light Sensor test *//*
Hardware configuration- Light Sensor connected to AI-31
*/
COMMENTS
MAIN PROG
7/27/2019 Interactive c Robot Manual En
69/120
69
GP2D12 Readings ( Package & Additional )
The GP2D12 Module sensorsare also Analog and therefore
use the same ports as the light
sensors.
Procedure
- Connect the GP2D12 Sensor to AI-6.- Make sure the Interactive C Program is opened. Select a NEW Program or continue
with your existing Program.- The Following Sample Code, GP2D12-CODE- After you have typed / inserted the code, click on the RUN MAIN button.
- Place an object in-front of the sensor.- Observe the LCD Screen on the Main Board.
- Move the object nearer and further from the sensor and observe the LCD Screenagain.
7/27/2019 Interactive c Robot Manual En
70/120
70
GP2D12 CODE
#define base -19float dis_table[118]={
/*distance value*//*ADC value*/
32.0,/*19*/ 30.1,/*20*/ 29.5,/*21*/ 28.6,/*22*/ 27.5,/*23*/26.1,/*24*/ 25.3,/*25*/ 24.5,/*26*/ 23.7,/*27*/ 23.2,/*28*/
22.3,/*29*/ 22.0,/*30*/ 21.1,/*31*/ 20.5,/*32*/ 20.0,/*33*/
19.3,/*34*/ 19.1,/*35*/ 18.4,/*36*/ 17.9,/*37*/ 17.5,/*38*/17.1,/*39*/ 16.5,/*40*/ 16.2,/*41*/ 15.8,/*42*/ 15.6,/*43*/15.5,/*44*/ 15.3,/*45*/ 14.8,/*46*/ 14.2,/*47*/ 13.8,/*48*/13.6,/*49*/ 13.3,/*50*/ 13.1,/*51*/ 12.8,/*52*/ 12.6,/*53*/
12.4,/*54*/ 12.2,/*55*/ 12.0,/*56*/ 11.8,/*57*/ 11.7,/*58*/
11.6,/*59*/ 11.6,/*60*/ 11.5,/*61*/ 11.4,/*62*/ 11.3,/*63*/10.85,/*64*/ 10.6,/*65*/ 10.3,/*66*/ 10.2,/*67*/ 10.0,/*68*/
9.8,/*69*/ 9.7,/*70*/ 9.5,/*71*/ 9.3,/*72*/ 9.2,/*73*/9.0,/*74*/ 8.9,/*75*/ 8.8,/*76*/ 8.6,/*77*/ 8.4,/*78*/
8.3,/*79*/ 8.2,/*80*/ 8.0,/*81*/ 7.85,/*82*/ 7.7,/*83*/
7.6,/*84*/ 7.5,/*85*/ 7.3,/*86*/ 7.2,/*87*/ 7.15,/*88*/7.1,/*89*/ 7.0,/*90*/ 6.9,/*91*/ 6.8,/*92*/ 6.7,/*93*/
6.6,/*94*/ 6.5,/*95*/ 6.4,/*96*/ 6.35,/*97*/ 6.3,/*98*/6.2,/*99*/ 6.15,/*100*/ 6.1,/*101*/ 6.0,/*102*/ 5.9,/*103*/5.85,/*104*/ 5.8,/*105*/ 5.7,/*106*/ 5.65,/*107*/ 5.6,/*108*/
5.55,/*109*/ 5.45,/*110*/ 5.4,/*111*/ 5.4,/*112*/ 5.3,/*113*/5.2,/*114*/ 5.1,/*115*/ 5.0,/*116*/ 5.0,/*117*/ 4.9,/*118*/
4.9,/*119*/ 4.8,/*120*/ 4.8,/*121*/ 4.7,/*122*/ 4.7,/*123*/4.6,/*124*/ 4.6,/*125*/ 4.5,/*126*/ 4.5,/*127*/ 4.4,/*128*/
4.4,/*129*/ 4.3,/*130*/ 4.3,/*131*/ 4.2,/*132*/ 4.2,/*133*/
4.1,/*134*/ 4.1,/*135*/ 4.0/*136*/
/* GP2D120 test*//*
Hardware configuration
- GP2D120 connected to AI-6*/
COMMENTS
DEFINITION
7/27/2019 Interactive c Robot Manual En
71/120
71
void main(){
int an; // Keep analog value from sensorwhile(1) // Infinite loop
{an = analog(6); // Read analog value from sensor
if(an>=19 && an
7/27/2019 Interactive c Robot Manual En
72/120
72
SRF04 Readings ( Additional )
The SRF04 has Signals, on input and
the other output For every output,there is an input for checking.
Procedure- Connect the Echo Input of the SRF04 to Digital Input Capture C-1 (IC1)
- Connect the Trigger Pulse output of the SRF04 to the Digital Input 9 (IN9)
- Make sure the Interactive C Program is opened. Select a NEW Program or continuewith your existing Program.
- The Following Sample Code, SRF04-CODE- After you have typed / inserted the code, click on the RUN MAIN button.- Place an object in-front of the sensor.
- Observe the LCD Screen on the Main Board.- Move the object nearer and further from the sensor and observe the LCD Screen
again.
7/27/2019 Interactive c Robot Manual En
73/120
73
SRF04 CODE
#use "srf04_lib.ic" /* Include library srf04_lib.ic*/
void main()
{ int result; // Declare keep input from touch sensor
sonar_init(); // Initial sonar sensor while(1) // Infinite loop
{
result= sonar_sample(); // Keep distance valueif (result != -1 ) // Check result value
printf("Distance %d cm\n", result); // Display distance cm scale else printf("Out of Range\n"); // Display massage when out of range
sleep(0.3); // Delay 0.3 sec for display}
}
/* Sonar sensor test*/
/*
Hardware configuration
- echo pulse pin connected to IC1
- trigger pulse pin connected to IN-9
*/
COMMENTS
MAIN PROG
7/27/2019 Interactive c Robot Manual En
74/120
74
Add senses to the Robo-11 standard so thatit can detect and move along a line, by usingthe IR Reflector Sensor.
1 Using the Robo-11 standard robot,remove the top structure that has the AX-11 attached.
2 Turn the robot upside down. Install the10 mm plastic spacer using a 3 x 25 mmscrew screwed into the universal plateaccording to the positions as shown in thepicture ( positions 5,2 and 5,9 : the firstset of numbers refer to the longitudepositions from the leftmost side while thesecond set is the horizontal positions
form the top down. )
3 Take two IR Reflector Sensors (ZX-03)and place them onto the spacers, twistingthe screw through the spacer and sensorand screwing it tightly together with a 3mm nut. Do the same for both sets, andset the robot upright.
Building Type 1
7/27/2019 Interactive c Robot Manual En
75/120
75
/* Example for Robo-11 liner1 : Black line DetectionHardware configuration- Motor left connected to DC Motor chanel M-0- Motor right connected to DC Motor chanel M-1
- ZX-03 left connected to AI-31- ZX-03 Right connected to AI-17 */
#define pow 50 /*Configuration power drive motor 50% */#define ref 70 /*Configuration analog reference 70 */int left=0,right=0; // To keep input analog value
void main(void){ao();while(!stop_button()) // Check STOP button pressed in process{printf(Press start!\n); // Show messagewhile(!start_button()); // Check START button pressed to run
printf( Track Line\n); // Show message for workingwhile(!stop_button()) // Check STOP button pressed in process{left = analog(31); // Read left sensor dataright = analog(17); // Read right sensor dataif((left>ref)&&(right>ref) //check out line{
run_fd(0.01); // Direct forward} else if((leftref)) // check left sensor in line{turn_right(1.5); // Turn right 1.5 sec
} else if((left>ref)&&(right
7/27/2019 Interactive c Robot Manual En
76/120
7/27/2019 Interactive c Robot Manual En
77/120
77
Create the test field by cutting two 20 cm long and 1 in wideblack tape and placing it 50 cm apart on a flat surface.
Testing It
Place the Robo-11 Liner1 on the floor and then turn on thePOWER switch. The LCD screen displays the message PressStart. Press START on the AX-11. The robot will moveforward using only 50% of its power, while using the IRReflector Sensor to detect the black line. The robot will
immediately change directions if it detects a black line, thedirection depending on the operation of the sensors.
If the left sensor detects the line first, the robot will turnright. However, if the right sensor detects the line first, it willturn left. If both sensors detect a line, the robot will also turnleft.
How accurate the Robo-11 Liner1 detects the black linedepends on the chosen decision variable, whether is defined
as the black line or the white surface. In the test program,the ref parameter is defined as 80. This value may bechanged depending on the test area, which may have moreor less light. Other factors may include the distance from thesensor to the floor, or if the test field is modified to havewhite lines on a black surface instead.
7/27/2019 Interactive c Robot Manual En
78/120
78
Building Type 2
1 The Robo-11 Liner2 will have 3 IRReflector sensors installed, enabling amore efficient detection. Using the Robo-11 standard robot, remove the topstructure that has the AX-11 attached.
2 Turn the robot upside down. Install the10 mm plastic spacer using a 3 x 25 mmscrew screwed into the universal plateaccording to the positions (5,2), (8,6)and (5,9). The first set of numbers refersto the longitude positions from theleftmost side while the second set is thehorizontal positions form the top down.
3 Place the IR Reflector Sensors (ZX-03)onto the spacers, twisting the screwthrough the spacer and sensor andscrewing it tightly together with a 3 mmnut. Do the same for all sets, and set therobot upright.
4 Replace the top structure with the AX-11board back onto the bottom part. Thenconnect the left IR Reflector Sensor(looking down from the top) to terminalAl-31 and the right one to terminal Al-17of the AX-11
7/27/2019 Interactive c Robot Manual En
79/120
79
Conditions in testing the Line Sensor
The programmer needs to test reading the values from the line sensor, in this case,detecting a black line and white surface. Then he must calculate the value that isable to differentiate between the reflection from the black line and the white fieldsurface. The program can be written as following:
void main(){
while(1) // Endless loop{printf(L=%dM=%d R=%d\n,analog(31),analog(25),analog(17));
// Reading all sensorssleep(0.1); // Display delay}
The test results in the following:
When the black line is detected, the converted analog signals to digital signals willgive a value of 40 to 60.
When the white surface is detected, the converted analog signals to digital signalswill give a value of 40 to 60.
Therefore, 80 is chosen as the reference value for the black line detection. Thus, ifthe value read from the line sensor is less than 80, the sensor will consider it to beon a black line. But if the value read is more than 80, than the sensor is consideredto be on the white surface area.
When the Robot Moves
Results of all sensors are as following:
Left Line Sensor Central LineSensor
Right Line Sensor
Detected whitesurface. The valueread from input Al-31 was more than80.
Detected the blackline. The valueread from input Al-25 was less than80.
Detected whitesurface. The valueread from input Al-17 was more than80.
When the robot operates in this scenario, the robot mustbe controlled so that it moves forward and delays briefly.
Scenario 1: Robot moves along the line
7/27/2019 Interactive c Robot Manual En
80/120
80
Scenario 2: The robot moves rightwards away of the line
Scenario 3: The robot moves leftwards away of the line.
Scenario 4: The robot meets an intersection
Results of all sensors are as following:
Left Line Sensor Central Line Sensor Right Line Sensor
Detected the blackline. The value readfrom input Al-31 was
less than 80.
Detected the blackline. The value readfrom input Al-25 was
more than/less than80.
Detected whitesurface. The valueread from input Al-
17 was more than80.
When the robot operates in this scenario, the robot must becontrolled so that it turns left slowly and delays briefly.
Results of all sensors are as fol