Robot C A Tutorial I OVERVIEW Overview 1
Robot. C – A Tutorial I
OVERVIEW Overview 1. Basic Introduction to the Programming Software 2. Introduction to Programming Concepts 3. Robot. C Specifics (next lecture)
SECTION 1 Section Overview Ø Explanation of the Integrated Development Environment (IDE) and its parts § Top Menubar § § § Side Functions Panel Code Window Error Window Ø Compile/Download code to the NXT Ø Run the code
SETUP IDE Explained Side Functions Panel Top Menubar Code Window Error Window
IDE Explained – Top Menubar Compile/Run SETUP Debug Sensor Setup Firmware Download All Help topics Variable Help Debugging help Web Help
SETUP IDE Explained – Side Functions Panel Drag and drop Functions list Explanation of the function
SETUP IDE Explained – Code Window Line Numbers Color coding to help identify different segments of the code. The colors can be changed from preferences menu In the top menubar Auto-complete feature Denotes errors/warnings
SETUP IDE Explained – Error Window Error line number Fatal Error Explanation of the cause of the error Warnings and general info, ignorable messages
SETUP Compiling/Running There are 4 basic steps in running a program 1. Download the firmware (a one-time step) – refer to textbook 2. Compile the program. This reports any errors and warnings 3. Load the program onto the NXT 4. Run program either from debugger window or the NXT directly
Compiling/Downloading Your Code SETUP ØTo compile AND DOWNLOAD your program, press F 5 ØTo compile WITHOUT downloading to NXT, press F 7 Compile the code If compilation reports errors, look at the error window and correct the errors. Then try compiling again.
SETUP Running Your Program Your program can be run by: Ø Clicking the Start button on the popup window - (if the NXT is connected to the computer) OR Ø Hitting the Orange button on the NXT – (if NXT is disconnected) Click the start button (This starts the debugger, covered in the next lecture. )
Basic Exercise SETUP Typing and running your first program. Use the steps you know to type the simple hello world program below, save the file and then run the code on the NXT. Don’t worry if you don’t understand the exact functioning of the program. You should just be able to use the IDE 1 task main () 2 { 3 nxt. Display. Text. Line(3, “Hello”); 4 nxt. Display. Text. Line(4, “World”); 5 while(true); 6 7 } Observe the output on the NXT screen
SECTION SUMMARY Summary Till now we have learned Ø Basic IDE features and whereabouts of various options Ø How to compile, load and run a program. With this level of familiarity, you should be able to try writing and running the code examples in the next few sections. Now to see some general programming concepts
SECTION 2 Section Overview § Programming Syntax Ø Ø Ø Capitalization Whitespaces Comments Variables Boolean Algebra § Control Structures Ø Ø Tasks Functions If-Else/Switch While/For
PROGRAMMING RULES General Rules Robot. C is a text-based programming language based on standard C programming language rules 1 task main () 2 { 3 motor[motor. A] = 50; 4 motor[motor. B] = 50; 5 wait 1 Msec(2000); 6 motor[motor. A] = -50; 7 motor[motor. B] = -50; 8 wait 1 Msec(2000); 9 See the regularity within the statements. It follows something called SYNTAX (formatting rules) that Robot. C understands } Code written in proper SYNTAX can be compiled and converted into machine code, which can be loaded onto the robot
PROGRAMMING RULES Keywords Robot. C has reserved a certain set of words that convey a special meaning to the compiler These cannot be used for any other purpose throughout the program. 1 task my. Task () NOT A KEYWORD 2 { You can use it and name it as you wish 3 int my. Var = 50; 4 motor[motor. A] = 50; 5 motor[motor. B] = my. Var; 6 wait 1 Msec(2000); 7 } KEYWORDS –Convey special meaning to the compiler Observe how the software trying to help you by color coding what it recognizes as a reserved word and what it doesn’t Blue, Red and Black
PROGRAMMING RULES Capitalization Using lowercase or UPPERCASE is significant in Robot. C 1 Task my. Task () NOT THE SAME 2 { The first of these represents the keyword for integer. 3 int my. Var = 50; 4 Int my. Bad. Var = 100; 5 motor[motor. A] = 50; 6 } DO NOT REPRESENT the intended meaning Will result in compiler errors The second one is an error. For variable names, it doesn’t matter which case you use if it’s the same throughout the program. Makes a difference for keywords
PROGRAMMING RULES Statements A set of commands make a statement It may be more than one line or several in one line 1 task my. Task () 2 { 3 int my. Var = 50; 4 motor[motor. B] = 50 5 motor[motor. A] = 50; 6 } Each of these lines represents one statement For the compiler, each statement is separated by a semicolon (; ) SYNTAX ERROR – No semicolon to end the intended statement Will result in compiler errors
PROGRAMMING RULES White spaces (space, tab, blank lines) are not interpreted by the compiler. Ø This means that you may use white spaces as per your liking – where you want, how many you want Ø Ø Use as necessary to organize your code better This DOES NOT mean that a white space may be used within a keyword or a variable. Ø in t and int are different my. Var and my Var are different
PROGRAMMING RULES Whitespaces The only difference in the two codes below is the use of whitespaces. Observe how easy it is to understand the second code as compared to the first one!! 1 task my. Task () 2 { 3 int Reading; 4 while (true) { 5 Reading = Sensor. Value(ls); 6 if (Reading > 40) { 7 motor[motor. A] = 50; 7 8 } else { 8 9 motor[motor. A] = -50; 9 10 } 10 11 } 11 12 } motor[motor. A] = 50; } else { motor[motor. A] = -50; } }
PROGRAMMING RULES Comments Commenting a program means using descriptive text to explain portions of code. It is very important to add good comments as it cuts down confusion for someone else, or even yourself at a later stage The compiler and robot both ignore comments when running the program. 1 task my. Task () 2 { 3 /* Modified by Shalabh 12/05 4 Start motor A first 5 */ 6 motor[motor. A] = 50; 7 // Start motor B 8 motor[motor. B] = 50; Multi line comments. Start by /* and end by */ Single Line comments. Start with a // end when you hit enter/return
PROGRAMMING RULES Comments One of the major uses of comments is to hide code from the compiler During the testing phase, you may not want the compiler to execute the entire code. Comments can be used to achieve this without having to delete lines 1 task my. Task () 2 { 3 //motor[motor. A] = 50; 4 motor[motor. B] = 50; 5 /* temp. Var = 20; 6 motor[motor. A] = temp. Var; 7 */ 8 } 9 10 If for some debugging purpose, you do not want motor A to operate, you can comment out all statements that have anything to do with motor A. Easier than deleting and retyping
PROGRAMMING RULES Punctuation, much like the English language is used to demarcate sections or convey special meaning. Ø Semicolon (; ) – Used to mark the end of statements Curly Braces { } – Used to mark the beginning and end of control structures Ø Square Braces [ ] – Used to denote special elements like array elements Ø Parenthesis ( ) – used to denote special elements like arguments passed to a function, or to define order-of-operations within a mathematical expression. Ø Observe the usage of these punctuations during various parts of the presentation
VARIABLES Variables are places to store values (such as sensor readings) for later use, or for use in calculations. Usage Steps Ø Create/Declare the variable int demo. Var, demo. Final=17; Ø Assign a value to the variable demo. Var = 10; Ø Use the variable for calculations or display demo. Final = demo. Var * demo. Var; Datatype Variable name Variable being assigned Variable being used for calculation
VARIABLES Variable Rules There are two rules that must be followed while defining variables Data Type - Defines the type of value that the variable holds Data Type Description Example Keyword Integer Positive and negative whole numbers -1, 29, 12, 13, 0 Floating Point Decimal Values or whole numbers 1. 2934, 1. 1, -123. 23 float String of characters “Daniel is a good guy” string Boolean A yes or no value true, false or 0, 1 bool Name Rules: A variable name can not have spaces in it A variable name can not have symbols in it A variable name can not start with a number A variable name can not be the same as a reserved word int
VARIABLES Variable Scope Variables declared at certain places can only be used within some limited area. This defines the scope of a variable There are two types of variables Ø Local: Those that are restricted to a function/task Ø Global: Those that can be accessed from anywhere Global Local main() Local my. Task()
VARIABLES Variable Scope Global variable. Can be used/modified anywhere Local variable. Can be used/modified only within the defining task Invalid statement. This variable belongs to other. Task. Cannot be modified here
MATH EXPRESSIONS Mathematical Expressions Multiplication: * int a = 3 * 4; Division: / float b = 12. 0 / 7. 0; Addition: + Subtraction: Precedence (order-of-operations): int c = (4 * 3 + 12 / 6); What is c? (12 + 2) = 14 int d = (4 * (3 + 12) / 6); What is d? (4 * 15 / 6) = 10 Others: % (modulo or remainder) pow() log() exp() sin() cos() tan()
BOOLEAN LOGIC Boolean Logic Certain operators are used to compare two variables and result in a true/false value. These are Boolean comparator operators EQUALITY: ( var == value/var 2 ) - Is the variable equal to value or another variable results in true if the two are equal eg: (a == 20) or (a == b) INEQUALITY: ( var != value/var 2 ) - Is the variable NOT equal to value or another variable results in true if the two are NOT equal eg: (a != 20) or (a != b) GREATER/LESS: ( var > value/var 2 ), ( var < value/var 2 ) – Is the variable greater than or less than the value or another variable results in true if the first value is greater (first case) than or less than eg: (a > 20) or (a <= b)
BOOLEAN LOGIC Boolean Logic Computers don’t understand the concept of ‘maybe’ like we do. For them, its either ‘true’ or ‘false’ eg: Are you enjoying this presentation? True/False Is your hovercraft going to fly? True/False Certain operators have results which are true or false OR: (condition 1) || (condition 2) - Is condition 1 true OR condition 2 true results in true if either of the two conditions is true eg: (a > 20) || (b <= 10) AND: (condition 1) && (condition 2) - Is condition 1 true AND condition 2 true results in true if both of the two conditions are true eg: (a > 20) && (b <= 10) NOT: ! (condition 1) – NOT the same result as condition 1 results in true if the condition is false, and vice versa eg: !(a > 20)
CONTROL STRUCTURES Programming Flow The general flow of execution of a program is on a sequential basis from the top to the bottom 1 task main () 2 { 3 motor[motor. A] = 50; 4 motor[motor. B] = 50; 5 wait 1 Msec(2000); 6 motor[motor. A] = -50; 7 motor[motor. B] = -50; 8 wait 1 Msec(2000); 9 } First motor A is started at 50% power Then motor. B is started at 50% power Then the program waits for 2000 msec Then the motor. A is reversed and run at power level 50 …an so on, the program continues The regular flow can however be modified to Ø Run some statements in parallel or Ø Exclude some statements from execution (conditioned) by the use of CONTROL STRUCTURES
CONTROL STRUCTURES Control Structures can be used to alter the flow of execution of the program Each control structure has a set of statements, delimited by the { } punctuation symbols. Ø Within each control structure, the statements are run sequentially Ø
CONTROL STRUCTURES Task Ø A Task allows execution of several set of statements in parallel. In general, tasks are used to run a constant sequence of commands which may not affect the functional logic of the program but just act as data-feeders Ø Ø Robot. C supports the definition of a maximum of 10 tasks Though tasks are run in parallel, running a large number of tasks tends to slowdown the overall performance of the system Ø Why? ? Because of various factors like scheduling overhead and processing overhead.
CONTROL STRUCTURES Task Example The following is an example, where a task may be useful. Consider the case where a sensor provides data about the rotation of the Robo. Car. A task can be designed to monitor the angle of turn and update a variable which can be used in the main logic Start Is the car deviating from desired direction? Get Data from the Gyro sensor Update Variable: angle. Of. Turn Yes Make Use of data from corrective turn task in decision making No Go Straight
CONTROL STRUCTURES Task The basic syntax of a task may be written as follows 1 task. Name 2 { 3 4 Task Punctuation set of statements to run } Program execution always begins at the main task. Hence it is mandatory to have that May have other control structures (not other task definitions though) Other tasks may be started or stopped from within the main task by using Start. Task(task_name); Stop. Task(task_name); A task must be defined before it is started or stopped => Tasks must be defined before main task
CONTROL STRUCTURES Functions are used primarily for reusing frequently occurring chunks of code (much like a task) There are some major differences between a task and a function Task Function Runs in parallel with the invoking code Runs sequentially with the invoking code Cannot accept arguments Cannot be run again without stopping previous instance Can be run as many times as needed without caring about previous instance
CONTROL STRUCTURES Functions - Terminology In functions terminology, Return parameter – This is the value that is computed inside the function and passed to the calling code. i. e. a value that gets assigned to some variable inside the calling code Function argument – This is the value which needs to get into the function but resides with the calling code. So it is passed to the function through a dummy variable
CONTROL STRUCTURES Functions The basic syntax of a function may be written as follows 1 return. Type func. Name(data. Type arg) 2 { 3 set of statements to run 4 return var. Name 5 } Function name The datatype of the value that the function is going to return Variable name corresponding to the return argument Variable name corresponding to the argument being passed Datatype of the argument that the function accepts
CONTROL STRUCTURES Functions Same name Names needn’t be the same The function argument and what gets used inside must have same name Names needn’t be the same This function would be used in a program that needs to square numbers several times.
CONTROL STRUCTURES If - Else An if-else Statement is one way to make a decision Program will check the (condition) and then execute one of two pieces of code, depending on whether the (condition) is true or false. 1 if (conditon) { 2 3 set of statements to run } else { 4 5 set of statements to run } Variable whose value is to be used for decision Set of statements to run if the condition evaluates to true, i. e. Boolean value 1 Set of statements to run if the condition evaluates to false, i. e. Boolean value 0 During each execution, only one of the if-else conditional statements will run i. e. Among all the set of statements, only one set will be run
CONTROL STRUCTURES If-Else Example Condition to be checked. If the value of the light sensor is greater than 50 or less than 50 If true, i. e. the value is greater than 50, go forward. Run these statements If false, i. e. the value is less than 50, go backward. Run these statements
CONTROL STRUCTURES Switch - Case The switch-case command is a decision-making statement which chooses commands to run from a list of separate “cases”. 1 switch (value) { 2 case value 1: 3 set of statements to run 4 break; 5 case value 2: 6 set of statements to run 7 break; 8 9 default: set of default statements Variable whose value is to be used for decision If the value of the variable is value 1, then Run the following statements Break – once done running these statements, come out of this structure Default – if none of the above matches, then run these 10 } During each execution, only one of the switch-case values is selected executed. i. e. Among all the set of statements, only one set will be run
CONTROL STRUCTURES Switch – Case Example The variable my. Var is used to decide between various cases If the value of my. Var is 1, run motor A forward with power 50 If the value of my. Var is 2, run motor A backward with power 50 Otherwise, run motor A forward at full power
CONTROL STRUCTURES If-Else/Switch-Case These seem similar and may be used interchangeably in many cases (but not always) The if condition can always be used to replace the switch condition (because number of switch conditions is always finite and generally small), but not vice-versa.
CONTROL STRUCTURES If-Else/Switch-Case Can you think of an example where the if statement may not be replaced by a switch statement? Try writing a switch case for a simple condition if ( temp. Var > 50 ) { // Do action 1 } else { // Do action 2 }
CONTROL STRUCTURES While A while loop is a structure which allows a portion of code to be run over and over, as long as a certain condition remains true. 1 while (condition) { 2 set of statements to run 3 set of statements to run 4 } Condition which is checked. As long as the condition is true, the loop is repeated. The condition must result in a Boolean (1 or 0) value Set of statements which are repeated again and again
CONTROL STRUCTURES While Example Condition to be checked. While the value of the global variable my. Flag is not equal to false/0, continually run the statements bool my. Flag = true; (my. Flag == true) my. Flag = (Sensor. Value(x) > THRESH); Statements to be run again and again Every while loop must have some condition that updates the test condition in a way such that at some point of time, the test condition becomes unsatisfied. Otherwise, the loop will run forever
CONTROL STRUCTURES For A for loop is a structure which allows a portion of code to be run over and over, as long as a certain condition remains true. It is quite similar to a while loop. The primary difference is that it has an initialization and update section within the loop definition 1 for (init; condition; increment) { 2 set of statements to run 3 set of statements to run 4 } Set of statements which are repeated again and again Initialization of the variable, done at the beginning of the loop Condition which is checked. As long as the condition is true, the loop is repeated. Updating the variable. Done after each iteration
CONTROL STRUCTURES For Example Initializing ‘i’ equal to 0 Condition to be checked. While the value of the variable ‘i’ is less than or equal to 10, continue running the loop Updating ‘i’ by 1 after every iteration Statements to be run again and again
SECTION SUMMARY Summary Till now you have learned Ø Ø The basic syntax of programming Basics about variables and usage Basic Boolean algebra for programming applications The various control structures ALL of these concepts (EXCEPT Tasks) are native C concepts which can be applied in all C based languages
QUESTIONS Questions? ? ?
Exercise 0 • Open up the sample code database • Try running something (good example: path following) • Modify it • See if your modifications worked
Exercise 1 – 5 Minutes • In the following code, find all of the errors. 1 task main(Check Light Sensor Value) 2 { 3 Int light ==0; 4 while(true) 5 ( 6 if(li ght < 45) 7 { 8 nxt. Display. Text. Line(3, “Too Low”) //Display “Too Low” 9 } 10 else(light > 50) 11 { 12 nxt. Display. Text. Line(3, “Too High”); /Display “Too High” 13 } 14 ) 15 }
Exercise 1 – 5 Minutes • Correct Code: 1 task main() 2 { 3 int light =0; 4 while(true) 5 { 6 if(light < 45) 7 { 8 nxt. Display. Text. Line(3, “Too Low”); //Display “Too Low” 9 } 10 else 11 { 12 nxt. Display. Text. Line(3, “Too High”); //Display “Too High” 13 } 14 } 15 }
BACKUP SLIDES
SETUP Firmware – What is it? It is the Operating System for your robot Think of what Microsoft Windows does to your computer other than make it hang!! It is an interface between the hardware (the robot) and the software (code that you write) Robot. C Program Compiler Compiled Code Firmware Robot Runs
SETUP Firmware – How to install? In case the NXT has some firmware that is not compatible with Robot. C or there is an upgrade available, the firmware on the brick would have to be updated. It can be done through a few simple steps Click on the Robot tab on the menu bar and select the Download Firmware option Before starting , make sure that your NXT is turned on and has enough battery
SETUP Firmware – How to install? Clicking the option will open a dialog box. Once the NXT is found, the F/W Download button will become active. Click the Download button Location of the NXT found Log of what is happening Clears anything present in the NXT buffer for loading Good idea to do before firmware update
SETUP Firmware – How to install? Select the latest version of the firmware available and click Open. Before this step, ensure that the battery of the NXT is at least 50% charged Latest firmware file
Firmware – How to install? SETUP Firmware should install successfully. Then close the firmware window Message Log Firmware successfully downloaded
PROGRAMMING RULES Syntax – 5 minute activity Take 5 minutes. Open any of the demo programs and do the following activities 1. Save the program under a different name File -> Save As -> <Your. Name>. c If this step is not done, then you may accidently overwrite the original code while experimenting. Caution: Every time the code is compiled, it is automatically saved. 2. Try to change the code and intentionally making some of those syntax errors we had talked about. You can try to - Remove semicolons - Introduce spaces between keywords - Try capitalization of certain words - Try changing keywords 3. Now try compiling the program to see the kind of error messages you get. To better identify, try introducing the errors one at a time. To Compile, simply hit F 7
CONTROL STRUCTURES For Example - Exercise If the code on the previous slide is run, How many times do you think the car will move? 10? ? ? WRONG The correct answer is 11 times Try counting the numbers from 0 to 10, both inclusive
CONTROL STRUCTURES While/For A while and a for statement can always be substituted for each other. The ‘for’ is being used as a while by dropping the initialization and update logic from the loop declaration
- Slides: 63