1 / 63

RobotC – A Tutorial I

RobotC – A Tutorial I. Overview. Basic Introduction to the Programming Software Introduction to Programming Concepts RobotC Specifics ( next lecture). OVERVIEW. Section Overview. Explanation of the Integrated Development Environment (IDE) and its parts Top Menubar Side Functions Panel

dillan
Download Presentation

RobotC – A Tutorial I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. RobotC – A Tutorial I

  2. Overview • Basic Introduction to the Programming Software • Introduction to Programming Concepts • RobotC Specifics (next lecture) OVERVIEW

  3. 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

  4. IDE Explained Top Menubar SETUP Side Functions Panel Code Window Error Window

  5. IDE Explained – Top Menubar Compile/Run Debug Sensor Setup Firmware Download SETUP All Help topics Variable Help Debugging help Web Help

  6. IDE Explained – Side Functions Panel SETUP Drag and drop Functions list 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 Denotes errors/warnings

  8. IDE Explained – Error Window Explanation of the cause of the error Fatal Error Error line number SETUP Warnings and general info, ignorable messages

  9. 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

  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.

  11. 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 (This starts the debugger, covered in the next lecture.)

  12. 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); } Observe the output on the NXT screen

  13. 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

  14. Section Overview • Programming Syntax • Capitalization • Whitespaces • Comments • Variables • Boolean Algebra • Control Structures • Tasks • Functions • If-Else/Switch • While/For SECTION 2

  15. 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; wait1Msec(2000); } 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. Keywords 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() { intmyVar = 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 KEYWORDS –Convey special meaning to the compiler

  17. 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 TaskmyTask() { intmyVar = 50; Int myBadVar = 100; motor[motorA] = 50; } PROGRAMMING RULES 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. 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() { intmyVar = 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 SYNTAX ERROR – No semicolon to end the intended statement Will result in compiler errors

  19. 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

  20. 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() { intReading; 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() { intReading; while (true) { Reading = SensorValue(ls); if (Reading > 40) { motor[motorA] = 50; } else { motor[motorA] = -50; } } } PROGRAMMING RULES

  21. 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; Multi line comments. Start by /* and end by */ Single Line comments. Start with a // end when you hit enter/return

  22. 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; */ }

  23. 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

  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 Variable being used for calculation Variable being assigned Variable being used for calculation

  25. Variable Rules There are two rules that must be followed while defining variables Data Type - Defines the type of value that the variable holds VARIABLES 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. 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 VARIABLES Global Local Local myTask() main()

  27. 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 * 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() MATH EXPRESSIONS

  29. 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

  30. 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

  31. 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; wait1Msec(2000); } 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 …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 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

  33. 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

  34. 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 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 No Yes Make corrective turn Update Variable: angleOfTurn Go Straight Use of data from task in decision making

  35. 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 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. 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

  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

  38. Functions The basic syntax of a function may be written as follows Variable name corresponding to the argument being passed 1 2 3 4 5 returnType funcName(dataType arg) { set of statements to run return varName } CONTROL STRUCTURES Function name Datatype of the argument that the function accepts The datatype of the value that the function is going to return Variable name corresponding to the return argument

  39. 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 This function would be used in a program that needs to square numbers several times.

  40. 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 } 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

  41. 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 If false, i.e. the value is less than 50, go backward. Run these statements

  42. 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: set of statements to run break; 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 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. 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 Otherwise, run motor A forward at full power

  44. 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

  45. 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 }

  46. 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 1 2 3 4 while (condition) { set of statements to run set of statements to run } CONTROL STRUCTURES Set of statements which are repeated again and again

  47. While Example Condition to be checked. While the value of the global variable myFlag is not equal to false/0, continually run the statements bool myFlag = true; CONTROL STRUCTURES (myFlag == true) 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. 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 for (init; condition; increment) { set of statements to run set of statements to run } 1 2 3 4 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. 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 Statements to be run again and again

  50. 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

More Related