Presentation is loading. Please wait.

Presentation is loading. Please wait.

Preprocessor Directives

Similar presentations


Presentation on theme: "Preprocessor Directives"— Presentation transcript:

1 Preprocessor Directives
Statements beginning with # are directives to the preprocessor. They DO NOT end with ; Before the program is compiled, the preprocessor copies these definitions into the code. These definitions are not required, but make the code easier to write and more readable if you want to change the port on which a sensor is connected, and that appears multiple times in the program, then a single change in the #define is all you need to make the change.

2 // tribot2.nxc - drive and turn
// motors #define LEFT OUT_A #define RIGHT OUT_C // how much time to spend turning or forward #define TURN_TIME #define STRAIGHT_TIME // speed to run a turned motor #define TURN_POWER 50 task main() { // start with both motors on OnFwd(LEFT, 75); OnFwd(RIGHT, 75); // repeat the following steps forever while(true) …… }

3 Programming Style Use indentation to visually group program blocks.
Use comments to document the program

4 // tribot2.nqc - drive and turn
// motors #define LEFT OUT_A ……… task main() { // start with both motors on OnFwd(LEFT, 75); OnFwd(RIGHT, 75); // repeat the following steps forever while(true) // turn right by slowing down the right wheel OnFwd(RIGHT, TURN_POWER); Wait(TURN_TIME); // resume going straight Wait(STRAIGHT_TIME); // turn left OnFwd(LEFT, TURN_POWER); }

5 Time NXC is a real-time programming language.
Time is measured in 1/1000 of a second #define TURN_TIME 2000 Will define the turning time to be 2 seconds

6 Using Time to Control Motion
Wait(3000); The program will wait at that statement for 3 seconds. The following program will drive straight for 4 seconds, then if OUT_A is attached to the left wheel, the left wheel will stop and the right wheel will continue to drive for 1second causing the tribot to stear toward the left. OnFwd(OUT_AB, 75); Wait(4000); Off(OUT_A); Wait(1000);

7 Generating a Random Number
NXC has a random number generating function Random(100); Generates a random integer between 0 and All numbers in the range are equally likely (uniform distribution) 100

8 NXC Functions So far we have seen several NXC functions. They have been associated with: Motors: OnFwd(arguments); Off(arguments); OnRev(arguments); Sensors SetSensorTouch(arguments); Mathematical Random(arguments);

9 All NXC functions begin with a capital letter
All NXC functions begin with a capital letter. As in SetSensorTouch, capitals are used to make them more readable. The number of arguments depend on the function. “Not eXactly C Programmers Guide” (by John Hansen) provides a reference to the language. The functions are grouped into categories.


Download ppt "Preprocessor Directives"

Similar presentations


Ads by Google