Download presentation
Presentation is loading. Please wait.
1
RobotC – A Tutorial I
2
OVERVIEW Overview Basic Introduction to the Programming Software
Introduction to Programming Concepts RobotC Specifics (next lecture) OVERVIEW Basic Introduction to the Programming Software You will become familiar with the programming environment and learn a few basic skills like compiling/running codes and digging for help Introduction to Programming Concepts You will learn basic concepts of C programming language like syntax, control structures, etc. RobotC Specifics (next lecture) You will learn to harness the full power of RobotC by using its variety of preprogrammed functions and directives. You will also be introduced to techniques for configuring and interfacing sensors. Additionally, you will learn debugging techniques and how to use the built in debugger.
3
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 SECTION 1 We’ll start buy learning about the software that we use to write our programs, also called an Integrated Development Environment, or an IDE. In this case we’ll be using RobotC as our IDE. We’ll then learn how to compile the code we write and download it to the NXT. And we’ll finally learn to run the code on the NXT.
4
SETUP IDE Explained Top Menubar Side Functions Panel Code Window
The IDE can be divided into various parts 1. Top Menu bar 2. Side functions panel 3. Error Window 4. Code Window Error Window
5
IDE Explained – Top Menubar
Compile/Run Debug Sensor Setup Firmware Download SETUP On the top menubar, the tab you’ll without a doubt need to use is the tab labeled “Robot.” Under this you will find options for compiling, running, debugging and downloading firmware onto the NXT. Perhaps the most under-rated tab on the menubar is the Help tab. It contains comprehensive help topics on everything from key commands for using the NXT to how to download your programs onto the NXT. The other tabs on the menubar are the file tab and the view tab. All the usual commands are under the File menu as well as access to sample programs. These sample programs can be a great source of knowledge if you find yourself stuck programming or debugging. The view tab contains options for setting some IDE preferences and other logging/viewing preferences All Help topics Variable Help Debugging help Web Help
6
IDE Explained – Side Functions Panel
SETUP Drag and drop Functions list The side functions panel contains a list of all the functions and variables you might use in your program. By scrolling through the trees found in this panel, you can drag and drop program terms into your program with their exact spelling and punctuation. Hovering over an item in the list brings up a short explanation of the function, making this list helpful in finding a function that you may be unfamiliar with. Explanation of the function
7
IDE Explained – Code Window
Color coding to help identify different segments of the code. The colors can be changed from preferences menu In the top menubar Line Numbers SETUP Auto-complete feature In the code window you will type your program. Once you begin typing a function or variable that the IDE recognizes in the code window, the IDE will attempt to Auto-Complete the term for you. Functions can also be dragged into the code window from the side functions panel. Denotes errors/warnings
8
IDE Explained – Error Window
Explanation of the cause of the error Fatal Error Error line number SETUP After you attempt to compile your program, if you have errors in it (and you probably will), the errors and warnings will be displayed in the Error Window. The color of the X marks next to each item denote the type of problem encountered. Also present is an indication of the line number of your code in which the error was encountered. Warnings and general info, ignorable messages
9
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 SETUP Now that you are familiar with the IDE, we’ll move on to how to compile and run a program. The first step is to update the firmware on the NXT. This should have already been done for your NXT’s and therefore this step can be disregarded. If you encounter any problems with this, there is information in your textbook, or you can speak to Kevin or myself. The next step is to compile the program. When you write your code, it is in a language you and I can understand. When you compile your code, it is translated to a language that the NXT understands, and therefore this must be done every time you download a new or modified program to the NXT. It is during this step that any errors or warnings will be reported to you in the error window. The third step is to download the program to the NXT, and once this is done, you can execute the program, either through the computer, or the NXT directly.
10
Compiling/Downloading Your Code
To compile AND DOWNLOAD your program, press F5 To compile WITHOUT downloading to NXT, press F7 SETUP Compile the code If compilation reports errors, look at the error window and correct the errors. Then try compiling again. If you want to compile AND download your program, you can either press F5 or click on “Compile and Download Program” in the “Robot” tab of the top menubar. To do this, the NXT must be turned on beforehand and it must be plugged into the computer with the USB cable. If you only want to compile your program without downloading it to the NXT, you can either press F7 or click on “Compile Program” in the “Robot” tab of the top menubar. To do this, the NXT does not need to be connected to the computer or be turned on. If errors are reported, you can check the error window for details, correct the problems, and then try compiling again.
11
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) SETUP Click the start button If you have executed the previous step correctly, the program should be loaded onto the NXT. You can either run the program by clicking start on the window that’s popped up on the computer screen, or if you disconnect your NXT from the computer, you can press the orange button on it. (This starts the debugger, covered in the next lecture.)
12
SETUP Basic Exercise 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 SETUP 1 2 3 4 5 6 7 task main () { nxtDisplayTextLine(3, “Hello”); nxtDisplayTextLine(4, “World”); while(true); } EXERCISE Have students each complete exercise, and get students in groups to share an NXT to download program to. Observe the output on the NXT screen
13
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 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
14
SECTION 2 Section Overview Programming Syntax Capitalization
Whitespaces Comments Variables Boolean Algebra Control Structures Tasks Functions If-Else/Switch While/For SECTION 2 In order to write code that can be compiled and run on an NXT, we need to be able to write the code in a particular language. We’re next going to go over the rules of this language, also known as syntax, as well as some common structures you’ll find useful.
15
PROGRAMMING RULES General Rules
RobotC is a text-based programming language based on standard C programming language rules 1 2 3 4 5 6 7 8 9 task main () { motor[motorA] = 50; motor[motorB] = 50; wait1Msec(2000); motor[motorA] = -50; motor[motorB] = -50; } See the regularity within the statements. It follows something called SYNTAX (formatting rules) that RobotC understands PROGRAMMING RULES Code written in proper SYNTAX can be compiled and converted into machine code, which can be loaded onto the robot
16
PROGRAMMING RULES Keywords Blue, Red and Black
RobotC 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. NOT A KEYWORD You can use it and name it as you wish 1 2 3 4 5 6 7 task myTask () { int myVar = 50; motor[motorA] = 50; motor[motorB] = myVar; wait1Msec(2000); } PROGRAMMING RULES 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 RobotC uses certain words to convey particular meanings. These words will mean the same thing in every single program you write. This means that you cannot use them for anything else other than their intended meaning. In this example, the words task, motorA, and motor are keywords. Other words in this example like myTask and myVar are not keywords, but rather user-defined terms. The programmer has selected these words to define certain tasks or variables. They can be named anything the programmer wishes. You’ll notice that the IDE colors different text either blue, red, or black, to denote if the word is a keyword or a user-defined term. KEYWORDS –Convey special meaning to the compiler
17
PROGRAMMING RULES Capitalization
Using lowercase or UPPERCASE is significant in RobotC NOT THE SAME The first of these represents the keyword for integer. The second one is an error. 1 2 3 4 5 6 Task myTask () { int myVar = 50; Int myBadVar = 100; motor[motorA] = 50; } PROGRAMMING RULES Coding in RobotC is case-sensitive. Two terms with different capitalization will mean two different things. In this example, “int” in lowercase is not the same thing as capitalized “int.” Additionally, RobotC does not recognize “Task” or “Int” as keywords when they are capitalized. When you are defining a variable, you may capitalize it or not. Just remember, if you refer to the variable with different capitalization as you when you defined it, RobotC will not recognize it as the same variable. For variable names, it doesn’t matter which case you use if it’s the same throughout the program. Makes a difference for keywords DO NOT REPRESENT the intended meaning Will result in compiler errors
18
PROGRAMMING RULES Statements A set of commands make a statement
It may be more than one line or several in one line 1 2 3 4 5 6 task myTask () { int myVar = 50; motor[motorB] = 50 motor[motorA] = 50; } Each of these lines represents one statement For the compiler, each statement is separated by a semicolon (;) PROGRAMMING RULES A command or a set of commands makes up a statement. Each statement must be separated from the next by a semi-colon at the end of the line. If your code is missing a semi-colon after a statement, the compiler will report errors. SYNTAX ERROR – No semicolon to end the intended statement Will result in compiler errors
19
PROGRAMMING RULES White spaces
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 myVar and my Var are different PROGRAMMING RULES White spaces are generally ignored by the compiler and can therefore be used to keep your code organized. The exception to this is that spaces may not be added in the middle of a term.
20
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 2 3 4 5 6 7 8 9 10 11 12 task myTask () { int Reading; while (true) { Reading = SensorValue(ls); if (Reading > 40) { motor[motorA] = 50; } else { motor[motorA] = -50; } 1 2 3 4 5 6 7 8 9 10 11 12 task myTask () { int Reading; while (true) { Reading = SensorValue(ls); if (Reading > 40) { motor[motorA] = 50; } else { motor[motorA] = -50; } PROGRAMMING RULES The compiler interprets these two codes identically, but notice how much easier it is to follow the logic in the code on the right.
21
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. PROGRAMMING RULES 1 2 3 4 5 6 7 8 task myTask () { /* Modified by Shalabh 12/05 Start motor A first */ motor[motorA] = 50; // Start motor B motor[motorB] = 50; Using comments is vital in writing code. You can use text to describe what each structure or statement is intended to do in english. By adding comments, it will be easier for you or someone else to modify, troubleshoot, or interpret your code. To insert a comment into your code, you have two options. You can insert multiple lines of comments by surrounding your comments with asterisks, and outside of that slashes. Your other option is to insert a single line comment by typing two slashes before the comment. You can insert this type of comment on its own line or to the right of a line of code. Multi line comments. Start by /* and end by */ Single Line comments. Start with a // end when you hit enter/return
22
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 PROGRAMMING RULES 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 re-typing 1 2 3 4 5 6 7 8 9 10 task myTask () { //motor[motorA] = 50; motor[motorB] = 50; /* tempVar = 20; motor[motorA] = tempVar; */ } You may also find it useful to “comment out” parts of your code. Sometimes when debugging or troubleshooting the logic of your code, it is useful to delete parts of your code. Instead of actually deleting your work, which you often will want later, you can leave the section in, but have the compiler skip over it. This can be done by making the section of code a comment.
23
PROGRAMMING RULES Punctuation
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 PROGRAMMING RULES Much like English, proper punctuation is vital to getting across the correct meaning of your code to the compiler. 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 You’ll want to note how these punctuations are used in the sample codes in the remainder of this presentation.
24
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 demoVar, demoFinal=17; Assign a value to the variable demoVar = 10; Use the variable for calculations or display demoFinal = demoVar * demoVar; VARIABLES Datatype Variable name Variable being assigned You will want to use variables to store a values for use later in your program. To use a variable, you first need to initialize it. You can do that by defining its datatype. In this case, we are defining demoVar and demoVarFinal as integers. Next you’ll see that we have set the variable demoVar equal to 10. Lastly, we have set demoVarFinal equal to demoVar times demoVar. When assigning a value to a variable, the variable goes on the left of equal sign and the value will go on the right. Variable being used for calculation Variable being assigned Variable being used for calculation
25
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 int Floating Point Decimal Values or whole numbers 1.2934, 1.1, float String String of characters “Daniel is a good guy” string Boolean A yes or no value true, false or 0, 1 bool VARIABLES In the last example we defined a variable as an integer. Not all data can be expressed as an integer. Therefore we have these four datatypes we can select to define a variable as. An integer is a positive or negative whole number and the keyword for it is “int.” A floating point is any real number. It’s keyword is “float.” A string is a string of characters. Generally you can use this to hold a statement. It’s keyword is, interestingly enough, “string.” Boolean is a value of true or false, 0 or 1. Its key word is “bool.” When you define a variable there are a few rules for naming it. 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 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
26
VARIABLES Variable Scope Global Local Local myTask() main()
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 VARIABLES Global Depending on where you define a variable, you can dictate how available that variable will be. If you declare a variable outside of a task, it is called a global variable. This means that the variable will be used and modified within any task. If the variable is defined within a task, it will only be available for use/modification within that task. If you refer to it in another task, the compiler will respond with an error. Local Local myTask() main()
27
VARIABLES Variable Scope Global variable. Can be
used/modified anywhere VARIABLES Local variable. Can be used/modified only within the defining task Invalid statement. This variable belongs to otherTask. Cannot be modified here
28
Mathematical Expressions
Multiplication: * int a = 3 * 4; Division: / float b = 12.0 / 7.0; Addition: + Subtraction: - Precedence (order-of-operations): int c = (4 * / 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() MATH EXPRESSIONS The C syntax for creating mathematical expressions is highly intuitive, based on grade school arithmetic, with precedence and scoping controlled through use of parentheses. For more advanced mathematical operations, a suite of functions are available, which generally take and return floating point values.
29
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/var2 ) - 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/var2 ) - 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/var2 ), ( var < value/var2 ) – 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 values are often used to control a program. Here is how we can generate boolean values using numbers (int or float) as inputs. To check EQUALITY between two values, you want to use two equal signs between the values. It will result in true if the two variables are equal. To check INEQUALITY between two values, you want to use an exclamation point followed by an equal sign between the values. It will result in true if the two variables are not equal. To check GREATER THAN OR LESS THAN, you want to use a greater than or less than sign between the values.
30
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: (condition1) || (condition2) - 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: (condition1) && (condition2) - 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: ! (condition1) – NOT the same result as condition 1 results in true if the condition is false, and vice versa eg: !(a > 20) BOOLEAN LOGIC We can use a number of operators to represent a number of logical arguments we may want to use in a program. The first is the OR argument. It is represented by the two vertical lines between the two conditions. It will result true if either condition is true. The AND argument is represented by two ampersands between the two conditions. It will result in true only if both conditions are true. The NOT argument is represented by an exclamation point before a condition. It will result in true if the condition is false.
31
CONTROL STRUCTURES Programming Flow
The general flow of execution of a program is on a sequential basis from the top to the bottom First motor A is started at 50% power 1 2 3 4 5 6 7 8 9 task main () { motor[motorA] = 50; motor[motorB] = 50; wait1Msec(2000); motor[motorA] = -50; motor[motorB] = -50; } CONTROL STRUCTURES Then motorB is started at 50% power Then the program waits for 2000 msec Then the motorA is reversed and run at power level 50 The program is generally executed from the top down. The first statements will be executed before the last. In this case,: First motor A is started at 50% power Then motorB is started at 50% power Then the program waits for 2000 msec Then the motorA is reversed and run at power level 50 AND SO ON… We can change the order of execution to run statements at about the same time or exclude statements by using control structures. …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
32
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 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
33
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 RobotC 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 A task allows for multiple statements to be run at virtually the same time. Generally, you will want to do this to run supporting commands such as updating sensor values. Remember though, the performance capacity of the NXT is limited. Running multiple tasks at once may slow your program down.
34
CONTROL STRUCTURES Task Example Use of data from task in decision
The following is an example, where a task may be useful. Consider the case where a sensor provides data about the rotation of the RoboCar. A task can be designed to monitor the angle of turn and update a variable which can be used in the main logic Start Start CONTROL STRUCTURES Is the car deviating from desired direction? Get Data from the Gyro sensor Yes No On the right is a flow chart representing the logic of someones program for a RoboCar. In the diamond, the program is to check the value of a sensor. This sensor value is being updated by another task being run parallel on the left on this slide. While the right side is running, the left side is also continuously running, updating the sensor value. Update Variable: angleOfTurn Make corrective turn Go Straight Use of data from task in decision making
35
CONTROL STRUCTURES Task
The basic syntax of a task may be written as follows 1 2 3 4 task taskName { set of statements to run } Task Punctuation CONTROL STRUCTURES May have other control structures (not other task definitions though) Program execution always begins at the main task. Hence it is mandatory to have that The syntax of a task includes the word “task” followed by the task name. Then the statements included in the task are enclosed in curly brackets. You must have a main task in your program which will be run first and you may not nest different tasks within others. You can command certain tasks to be started or stopped, but the task must be defined above the command. Other tasks may be started or stopped from within the main task by using StartTask(task_name); StopTask(task_name); A task must be defined before it is started or stopped => Tasks must be defined before main task
36
CONTROL STRUCTURES Functions
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 CONTROL STRUCTURES Task Function Runs in parallel with the invoking code Runs sequentially with the invoking code Cannot accept arguments Can accept arguments Cannot be run again without stopping previous instance Can be run as many times as needed without caring about previous instance Similar to a task is a function. A function is to be used when you would otherwise be frequently reusing a chunk of code. The difference is that a function is run sequentially within the code that calls it rather than parallel like a task. Also, a function can accept input values and does not need to be stopped after running it.
37
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 For a function, the return parameter is the output value of the function. It is a value that gets assigned to some variable inside the calling code. The function argument is the input value of the function. It is passed to the function.
38
CONTROL STRUCTURES Functions
The basic syntax of a function may be written as follows 1 2 3 4 5 returnType funcName(dataType arg) { set of statements to run return varName } Variable name corresponding to the argument being passed CONTROL STRUCTURES Function name Datatype of the argument that the function accepts The datatype of the value that the function is going to return To write a function, you must first dictate the datatype that the function output will be, followed by the user-defined name of the function. After this goes the datatype for the input value and then the variable name that will refer to the input value. After this, enclosed by curly brackets, goes the statements that make up the function. To define the output value, you want to include a statement that says “return” and then the variable name assigned to the value you want the function to output. Variable name corresponding to the return argument
39
CONTROL STRUCTURES Functions
Same name The function argument and what gets used inside must have same name Names needn’t be the same CONTROL STRUCTURES Names needn’t be the same Here is an example of a function. What is the name of this function? -- “getSquare” What is the datatype of the input value? – “integer” What is the datatype of the output value? – “integer” What will result be set equal to in the main task? – 100 (10*10) Any questions on what is happening in this example? This function would be used in a program that needs to square numbers several times.
40
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. Variable whose value is to be used for decision CONTROL STRUCTURES 1 2 3 4 5 if (conditon) { set of statements to run } else { } Set of statements to run if the condition evaluates to true, i.e. Boolean value 1 If you want the program to run different statements depending on a varying condition, you may want to use an If–Else construct. The syntax of this construct requires the condition to be checked be placed in parenthesis after the word “if” following this, enclosed in curly brackets, the statements to be run if the condition is found to be true. If you would like to run another set of statements if the condition is not found to be true, you can follow the same format but with an else instead of the “if.” No additional condition is needed. Both the “if” and “else” statements will never run during a single execution, as a condition cannot be true and untrue at once. 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
41
CONTROL STRUCTURES If-Else Example
Condition to be checked. If the value of the light sensor is greater than 50 or less than 50 CONTROL STRUCTURES If true, i.e. the value is greater than 50, go forward. Run these statements Can someone tell me what condition is being checked in this if statement? – if variable lightSensorValue is greater than 50 What will occur if the condition is true? – Both motor A and motor B will run at 50 What will occur if the condition is false? – Both motor A and motor B will run at -50 If false, i.e. the value is less than 50, go backward. Run these statements
42
CONTROL STRUCTURES Switch - Case
The switch-case command is a decision-making statement which chooses commands to run from a list of separate “cases”. Variable whose value is to be used for decision 1 2 3 4 5 6 7 8 9 10 switch (value) { case value1: set of statements to run break; case value2: default: set of default statements } If the value of the variable is value1, then Run the following statements CONTROL STRUCTURES Break – once done running these statements, come out of this structure The switch case causes the program to select a set of statements to run based on a variable’s value. To use the construct, you can define a case for each value that the variable might hold as well as an “else’ type of case which will be run if none of the other cases are true. The syntax of the switch-case construct is the word “switch” followed by the variable being check enclosed in parenthesis. Then within one set of curly brackets, each case is defined. This is done by the word “case” followed by the value for that case and a colon. After the colon you may write the list of statements you would like to be executed if the case is true. For the “else” type case, just type “default” followed by a colon. The statements after this will be run if none of the cases defined are found. Just like the If-Else construct, only one case can run for each execution of the construct. Default – if none of the above matches, then run these 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
43
CONTROL STRUCTURES Switch – Case Example
The variable myVar is used to decide between various cases CONTROL STRUCTURES If the value of myVar is 1, run motor A forward with power 50 If the value of myVar is 2, run motor A backward with power 50 Can someone tell me what variable is dictating which case we follow? – myVar What will occur if myVar=2? – Motor A will run at -50 What must myVar equal if the motor is run at 50? – myVar must equal 1 What must myVar equal if the motor is run at 100? – myVar must not equal 1 or 2 Otherwise, run motor A forward at full power
44
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 You will sometimes be able to use the If-Else and Switch-Case constructs interchangeably. These two codes are equivalent. Can someone tell me which one is more versatile? - 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.
45
CONTROL STRUCTURES If-Else/Switch-Case
Can you think of an example where the if statement may not be replaced by a switch statement? CONTROL STRUCTURES Try writing a switch case for a simple condition if ( tempVar > 50 ) { // Do action 1 } else { // Do action 2 } Can you think of an example where the if statement may not be replaced by a switch statement? It is not possible to handle all negative and positive values of tempVar within a switch-case structure.
46
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. 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 CONTROL STRUCTURES 1 2 3 4 while (condition) { set of statements to run } 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. The syntax, similar to the other constructs, includes the word “while,” followed by the condition to check enclosed in parenthesis. As long as this condition is true, the statements enclosed in curly brackets below will repeat. When the condition is no longer true, execution will exit the loop. Set of statements which are repeated again and again
47
CONTROL STRUCTURES While Example Condition to be checked.
While the value of the global variable myFlag is not equal to false/0, continually run the statements CONTROL STRUCTURES bool myFlag = true; (myFlag == true) Can someone tell me what condition is being checked? – If variable numberOfIter is less than 20 What statements are being repeated while the condition is true? – Lines 7-10 Which line updates the variable being checked (governs the condition remaining true)? – Line 10 myFlag = (SensorValue(x) > THRESH); 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 Statements to be run again and again
48
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 CONTROL STRUCTURES Initialization of the variable, done at the beginning of the loop 1 2 3 4 for (init; condition; increment) { set of statements to run } Similar to the while construct, a for loop also allows a portion of code to be run over and over until a condition is no longer true. The difference is that the for loop has an initialization and update section for a variable within the loop definition. This variable dictates the number of repeats of the code below. The syntax of the for loop begins with the word, “for” Following this, enclosed in parenthesis, is the initialization of the variable, the condition to check, and the increment to change the variable by. After this goes the statements to be looped enclosed by curly brackets. Condition which is checked. As long as the condition is true, the loop is repeated. Set of statements which are repeated again and again Updating the variable. Done after each iteration
49
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 CONTROL STRUCTURES Updating ‘i’ by 1 after every iteration What variable is controlling the repetition of the structure and what is it set to initially? – variable i equals zero At what condition will the loop be exited? – When i is greater than 10 Notice that the “i++” indicates that i should be increased by one each time the loop is run. What lines are to be looped through? – Lines 6 & 7 Statements to be run again and again
50
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 SECTION 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. Many of the things you’ve learned today can in fact be applied to other languages like Java and Perl.
51
Questions??? QUESTIONS
52
Exercise 0 Open up the sample code database
Try running something (good example: path following) Modify it See if your modifications worked Line 1 “task main(Check Light Sensor Value)“ should be “task main()” Line 3 “==“ should be “=“ Line 3 “Int” should be “int” Line 5/15 “(“ / “)” should be “{“ / ”}” Line 6 “li ght” should be “light” Line 8 needs a “;” at the end Line 10 “else(light > 50)” should be “else” Line 12 “/Display” should be “//Display” Line 14 “Light” should be “light”
53
Exercise 1 – 5 Minutes In the following code, find all of the errors.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 task main(Check Light Sensor Value) { Int light ==0; while(true) ( if(li ght < 45) nxtDisplayTextLine(3, “Too Low”) //Display “Too Low” } else(light > 50) nxtDisplayTextLine(3, “Too High”); /Display “Too High” ) Line 1 “task main(Check Light Sensor Value)“ should be “task main()” Line 3 “==“ should be “=“ Line 3 “Int” should be “int” Line 5/15 “(“ / “)” should be “{“ / ”}” Line 6 “li ght” should be “light” Line 8 needs a “;” at the end Line 10 “else(light > 50)” should be “else” Line 12 “/Display” should be “//Display” Line 14 “Light” should be “light”
54
Exercise 1 – 5 Minutes Correct Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
15 task main() { int light =0; while(true) if(light < 45) nxtDisplayTextLine(3, “Too Low”); //Display “Too Low” } else nxtDisplayTextLine(3, “Too High”); //Display “Too High” What condition must be true for this code to end/exit the loop? – It will never exit the loop. It is looping while “true.” As long as “true” evaluates as “true” (it always will) the loop will continue.
55
BACKUP SLIDES BACKUP SLIDES
56
It is the Operating System for your robot
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) SETUP RobotC Program Compiler Compiled Code Firmware Robot Runs
57
Firmware – How to install?
In case the NXT has some firmware that is not compatible with RobotC 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 SETUP 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
58
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 SETUP 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
59
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 SETUP Latest firmware file
60
Firmware – How to install?
Firmware should install successfully. Then close the firmware window Message Log SETUP Firmware successfully downloaded
61
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 -> <YourName>.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 F7 PROGRAMMING RULES Exercise: Can be done individually. Students do not need an NXT.
62
CONTROL STRUCTURES For Example - Exercise
If the code on the previous slide is run, How many times do you think the car will move? CONTROL STRUCTURES If the code on the previous slide is run, How many times do you think the car will move? The moral is to be careful with the conditions you set in your code. 10??? WRONG The correct answer is 11 times Try counting the numbers from 0 to 10, both inclusive
63
CONTROL STRUCTURES While/For
A while and a for statement can always be substituted for each other. CONTROL STRUCTURES A while and a for statement can always be substituted for each other. These two codes will execute identically. In the second construct, the ‘for’ is being used as a while by dropping the initialization and update logic from the loop declaration. The ‘for’ is being used as a while by dropping the initialization and update logic from the loop declaration
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.