Presentation is loading. Please wait.

Presentation is loading. Please wait.

Wednesday Program Flow

Similar presentations


Presentation on theme: "Wednesday Program Flow"— Presentation transcript:

1 Wednesday Program Flow

2 Program Flow Robots are often asked to perform highly repetitive tasks. Programmers can take advantage of this fact by writing code that repeats itself as well

3 Compare these two examples

4 Conditional Loops Repeat Forever Repeat for a count

5 Conditional Loop Use the repeatUntil command block to make a loop conditional to different sensor input

6 Program Flow Watch the videos in the “Loops” section and complete the Square Dance Mini Challenge.

7 Challenge: RoboMower Complete the ”RoboMower Challenge”
First “flowchart” or plan your program Then program your robot If finished early… Think… what commercial products work in a similar manner? How you could make your program more efficient?

8 If/Else conditional block
An if-else conditional block is one way you allow a computer to make a decision. With this command, the program will check the (condition) and then execute one of two pieces of code, depending on whether the (condition) is true or false. If/Else conditional blocks typically need a repeat loop as well! Otherwise, the If/Else statement will only be checked once and the program will continue onwards.

9 If/Else conditional block
If the condition is true, the program will run the If branch In this case, turn right

10 If/Else conditional block
If the condition is NOT true, the program will run the else branch. In this case, move forward

11 If/Else conditional block
Remember, without the repeat block, the robot only makes the decision ONCE. With the repeat block, the robot checks the condition throughout.

12 Program Flow Watch the videos under If Else conditional block. When done, we will do the color sensor comparison

13 Program Flow Repeated Decisions
Watch the videos in the VEX IQ curriculum on “Repeated Decisions” Need to learn how to construct a program that continuously checks the sensors to ensure continuous program flow

14 Why will this code not work?
Repeated Decisions Why will this code not work?

15 Why will this code not work?
Repeated Decisions Why will this code not work?

16 Repeated Decisions

17 Repeated Decisions

18 Program Flow—Line Tracking
Everyone’s favorite activity—we’ve gone from this:

19 Program Flow—Line Tracking
To this: First number is the threshold. The second two numbers tell us how sharp of a turn we are making while tracking the line. For this example (100, 0), the robot is turning very sharply as it is line tracking. When would we want to line follow sharply? Watch the videos in the Line Tracking section…then begin to experiment with the lineTrack command block

20 Thursday Full ROBOTC

21 NOTE: These slides beyond this point have not been modified for VEX IQ specifically…

22 ROBOTC Rules/Syntax What does every program have to have?
task main() Set of "Curly Braces“ {} In what order does ROBOTC run a program? Sequentially – Top to Bottom What is whitespace? Space in a program to make it easier for a human to read. Simple Robot Commands (statements) always end with a…? Semicolon ;

23 ROBOTC Rules/Syntax Paired Punctuation Control Structures Comments
Some functions have "square brackets“ [] , other have "parenthesis“ () How do I keep them straight? Memorization Functions Library Control Structures Just like task main, they have a set of curly braces defining their beginning and end. {} Example? Comments //Necessary Evil Get into the habit now, or you won't do it ever Your students learn their habits from you…

24 ROBOTC Rules/Syntax Syntax is the cause of 80% of programming errors…
Most important thing to do when troubleshooting: Check Syntax Missing Semicolons Incorrect Braces on Structures Misspelled words Improper ‘case’ – motor vs. MoToR ROBOTC is friendly about most of these errors... but can’t catch everything.

25 Moving Motors Setting Motors Speed
To make a motor move, we’ll need to tell at what speed to travel. setMotorSpeed(motorIndex, velocity); This command will set the speed of a motor MotorIndex: the name or port of the motor Velocity: Any value between -100 and +100 Positive Numbers: Motor moves clockwise Negative Numbers: Motor moves counter-clockwise Zero: Motor will come to a stop Velocity roughly relates to RPM Velocity 50 = Approx. 50 RPM

26 Moving Motors Setting a motor speed does not tell the robot “how long” to move at that speed Typically all “SetMotorSpeed” commands are paired with a “sleep” command to specify how long to move at that specific speed. sleep(milliseconds); This command will tell the VEX IQ brain not to execute any additional commands until it has slept/waited for the specified amount of time. Sleep commands are important ROBOTC will automatically shut down any running motors once it reaches the end of a program.

27 Moving Motors

28 Moving Motors

29 Moving Motors We can move forward and backwards, go ahead and explore the commands and make the robot turn.

30 Moving Distances With integrated encoders, we can have our robot travel for a distance as opposed to a fixed amount of time. setMotorTarget(motorIndex, position, velocity); This command will move the motor to a specific position at a specified speed. motorIndex: the name or port of the motor position: the distance (in encoder counters) the motor should travel. 1 Rotation of the Motor = 360 Counts/Degree Velocity: Any value between -100 and +100 After the motor has traveled to the specified position, it will come to a stop automatically.

31 Moving Distances Timing? waitUntilMotorStop(motorIndex);
If we’re moving a specific distance, we still need to give the program time to run. How long to move to one rotation (360 counts/degrees)? How long to move to ten rotations (3600 counts/degrees)? How long will it take if you move at a faster or slower speed? waitUntilMotorStop(motorIndex); This command will “sleep” your program until the specified motor (motorIndex) comes to a stop. You can use this command to avoid providing a wait time – the command will intelligently wait until the motor informs it “I am done moving!”

32 Moving Distances Notice that we have to reset the encoders

33 Moving Distances Notice I do not need to include a command to reset the encoders

34 Moving Forward--Challenges
Apply what you have learned to solve these two challenges. Use encoders (rotation sensor) and the other sensors you have at your disposal.

35 Robo 500 Challenge Notice the Large Book on the tables?
Complete the "Robo 500 Challenge” First “flowchart” or plan your program Then program your robot If finished early… Make sure your code is commented Try to make the robot turn around and complete the Robo500 in reverse.

36 Challenge: Labyrinth Complete the ”Labyrinth Challenge”
First “flowchart” or plan your program Then program your robot If finished early… Make sure your code is commented

37 Code—Robo 500 with Gyro

38 Variables What is a variable? How do they work?
A variable is a facility for storing data in a program. How do they work? When a variable is “declared”, the compiler sets aside a piece of memory to store the variable’s numeric value. When the variable is called, the processor “retrieves” the numeric value of the variable and “returns” the value to be used in your program in that specific location.

39 Variables How do I create a variable?
To create (“declare”) a variable you need 3 things. Decide the data type of the variable (more on this soon) Give the variable a name Assign the variable a value (optional, but recommended) Example: int myVariable = 1000; Type: Integer Name: myVariable Value: 1000

40 Data Types There are 8 different types of variables in ROBOTC
Integer (int) – Memory Usage: 16 bits / 2 bytes Integer Numbers Only Ranges in value from to Long Integer (long) – Memory Usage: 32 bits / 4 bytes Ranges in value from to Floating Point (float) – Memory Usage: 32 bits / 4 bytes Integer or Decimal Numbers Variable precision, maximum of 4 digits after decimal

41 Data Types There are 8 different types of variables in ROBOTC
Single Byte Integer (byte) – Memory Usage: 8 bits/1 byte Integer Numbers Only Ranges in value from -128 to +127 Unsigned Single Byte Integer (ubyte) – Memory Usage: 8 bits / 1 byte Ranges in value from 0 to +255 Boolean Value (bool) – Memory Usage 4 bits / .5 bytes True (1) or False (0) values only.

42 Data Types There are 8 different types of variables in ROBOTC
Single Character (char) - Memory Usage: 8 bits / 1 byte Single ASCII Character only Declared with apostrophe – ‘A’ String of Character (string) - Memory Usage: 160 bits / 20 bytes Multiple ASCII Characters Declared with quotations – “ROBOTC” 19 characters maximum per string (NXT Screen limit)

43 Variables Some additional notes
Adding “const” in front of a variable will make that variable a constant. This will prevent the variable from being changed by the program Constants do not take up any memory on the VEX IQ The VEX IQ has room for 7500 bytes of variables

44 Variables Some additional notes
Variable’s names must follow a specific rules:

45 Using Variables Variables can be used in your program anywhere!
Motor Speeds, If/Else Loops, Conditional Statements Commands you know act just like variables SensorValue – Returns the value of a sensor value Variables are just numbers You can perform math operations on variables newVariable = oldVariable + 15;

46 Using Variables VS.

47 Repeating Code… Copy and pasting only works so well.
What if we could make each behavior one line of code?

48 Functions What is a function? How does a function work?
A function (or subroutine) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code. How does a function work? A function has to be first “declared” in your program, with code inside of the function. Once the function is created and “declared” it can then be “called” from task main or another function to be executed.

49 Creating Functions Set the “type” of function by declaring the “data type” of the function. Void is a special data type which means no value will be returned Give the function a name. Following the same rules that variable have! Add a set of parenthesis and curly braces Parenthesis are used for “parameters” – We’ll cover this soon. Curly braces define the beginning and end of the function.

50 Using Functions Once the function is created, “call” the function inside of task main by referencing the name and passing any parameters. Don’t forget your semicolon Note: Keep functions above task main, or else you will have to “prototype your function”.

51 Functions and Variables
Key Concept: Variable “Scope” Variables are “local” to where they are declared. Just because “speed” exists in “task main” doesn’t mean it can be used in a function. “speed” is currently localized to only “task main”

52 Functions and Variables
Solution #1 – “Globalization” Setting the variable outside any function will cause it to become a “global” variable. This is not an ideal solution because multiple functions can use and modify this variable! Use sparingly, but don’t be afraid to use it…

53 Functions and Variables
Solution #2 – “Passing Values” Instead of using the variable, we can just pass the value as a parameter to our function instead. This method is ideal because it gives you flexibility in your functions. This requires us to edit our existing functions, however.

54 Functions and Variables
Variables are now declared inside of the parameter field of the function. Multiple variables are separated by a comma. Variables are used inside of the function, but are localized to this function only. Each time the function is called a different value can be passed. This promotes code flexibility and reuse!

55 Other Function Types Functions don’t always have to be a “void” function. You can use any data type that you would assign to a variable! – int, float, bool, etc. A special command “return” is required to return a value back to the parent function.

56 Other Function Types Instead of “void” this function uses “int”. This tells us that this function will return an integer result. After we add 10 to the parameter value that was passed to use by task main, we send the new value back by using the “return” command. We assign the returned value to a variable so we can use the Debugger to verify the correct value was returned.

57 Other Function Types

58 Other Function Types

59 Creating a Function Library
Make sure you save in the same place Suppress warnings for unused functions #pragma systemFile

60 Global Variables Debugger

61 Self Paced Lesson - Using the Debugger
Watch the following lesson video: Variables – Debugging – Debugging Techniques When finished... Start converting your existing code into functions with parameters. Make sure you do this in a copy of your original programs so you don’t lose any existing work. Note: If in “Natural Language” mode, it may do random things – switch back to Normal Vex IQ programming!

62 ROBOTC Debugger Code Execution Control
Breakpoints – Allow us to stop our program at specific points to let us investigate the status of our code, variables, motors and sensors. Step Into – Used to step through all code and step into functions. Step Over – Jumps over a function, but stills runs it at full speed. Step Out – Jumps outside of a function or subroutine and returns to the calling function. Still executes all code, just at full speed until the function is exited. Clear All – Clears all the values of the motors, encoders, variables and sensors.

63 Constant Variables The NXT has a limited amount of space available for variables It’s best to intelligently use variables to preserve as much of this space as possible Constant variables and #define statements can help: Adding “const” to any variable will make it a compile-time constant and not use any variable space. A #define statement will create an alias to a value or statement in a single variable name.

64 Constant Variables Examples:

65 Variable Locations It is important where you declare your variables:
Variables declare outside of any structure (function or task) are considered to be “global” Variables declared inside of any structure (function to task) are considered to be “localized” to that structure. Variables declared in a loop/conditional statement are localized to that statement block It is always best to declare your variables in the correct location (usually at the top of your structure)

66 Variable Locations In this example, “test2” is not known outside of the “if” statement block.

67 Arithmetic Operators ROBOTC accepts a number of arithmetic operators:
Assignment: a = b Addition: a + b Subtraction: a – b Multiplication: a * b Division: a / b Modulo (remainder): a % b Increment: ++x, x++ Decrement: −−x, x−− Unary Positive: +x Unary Negative (inverse): −x

68 Arithmetic Operators Differences between ++i and i++
++i will increment the value of i, and then return the incremented value i++ will increment the value of i, but return the pre-incremented value.

69 Comparison Operators ROBOTC supports 6 different comparison/relational operators between two values: Equal to: a == b Not Equal to: a != b Greater than: a > b Less than: a < b Greater than or equal to: a >= b Less than or equal to: a <= b

70 Logical Operators ROBOTC has 3 logical operators to assist when making complex decisions: Logical Negation (NOT): !a Logical AND: a && b Logical OR: a || b

71 Logical Truth Tables AND (&&) OR (||) NOT (!)

72 If/Else Statements If the “while(true)” loop was missing, this code would only execute the “if” or “else” section once.

73 If/Else Statements If statements do not require an “else” statement.
If the “if” statement is false, it will just be skipped over. You can also make a multiple decision “if/else” statements. Example on the right 

74 Make your code more readable by using the “else if(condition)” command
“else if” Shorthand Make your code more readable by using the “else if(condition)” command

75 If/else Shorthand You can also have a single line “if” statement with out the need for curly braces “{“

76 For Loops “For Loops” are important for repeating a block of a code a certain number of times. For loops require a specific structure:

77 For Loops For Loop Syntax:
Initial – The variable that will be used to count the number of iterations through the loop Example: int i = 0; Condition – The conditional statement to decide how many iterations to loop through Example: i < 10; Increment – The statement to modify the counter variable through each iteration of the loop. Example: i++ No semicolon at the end of this increment portion

78 For Loops Drive and Turn – Loops 10 Times

79 For Loop Walkthough Create the for loop initial variable
Check the condition of the for loop If true, continue onward If false, skip the “for” loop Run code inside of “for” loop Run the iteration code and increment “i” by one. Loop steps 2-4 until 2 returns false.

80 Loop Control Two control statements are available to you when using “while” and “for” loops: continue; - skips any remaining code below the continue statement and proceeds with the next iteration in the loop. break; - breaks out of the current looping structure and proceeds execution of the rest of the program.

81 Loop Control The continue statement will cause the robot to keep moving forward until the touch sensor it pressed. The break statement will end the infinite while loop if the touch sensor is pressed

82 Thursday Final Challenge
Complete the ”Minefield Challenge” First “flowchart” or plan your program Then program your robot If finished early… Make sure your code is commented Read the Wikipedia article on “Code Refactoring” If you run out of time, this will be the warm up tomorrow morning.

83 Friday Remote Control, LCD, Sound

84 Playing Sounds VEX IQ Speaker
The VEX IQ system has a built in speaker that allows you to play tones and built in sounds. You will need to make sure sound is enabled on your VEX IQ: At the main menu, go to “Settings” (press the “X” button) The top option in the settings should say “Sound On” If it doesn’t press the “Check” button to toggle the sound “on” VEX IQ Speaker

85 Playing a Sound Effect playSound(nameOfSound); This command will play a built-in sound effect once. Parameter Description Default Value nameOfSound Specify the name of the sound effect you would like the VEX IQ system to play. The name of the sound files are below: soundSiren2 / soundWrongWay / soundWrongWays soundGasFillup / soundHeadlightsOn / soundHeadlightsOff soundTollBooth / soundCarAlarm2 / soundTada soundGarageDoorClose / soundRatchet / soundAirWrench soundSiren4 / soundRatchet4 / soundCarAlarm4 soundPowerOff2 N/A

86 Sound Examples Play the sound effect “Air Wrench”
playSound(soundAirWrench); sleep(500); Play the sound effect “Tada” playSound(soundTada); sleep(500); Note: Sounds typically need a “Sleep” time to give them time to actually be played.

87 Playing a Sound Effect Repeatedly
playRepetitiveSound(nameOfSound, duration); This command will play a built-in sound effect multiple times for a specified amount of time. Parameter Description Default Value nameOfSound Specify the name of the sound effect you would like the VEX IQ system to play. The name of the sound files are listed previously. N/A duration This is how long to play the sound effect for. This amount of time is in 10s of milliseconds (100 = 1 second)

88 Sound Examples Play the sound effect “Air Wrench” repeatedly for 1 second. playRepetitiveSound(soundAirWrench, 100); sleep(1000); Play the sound effect “Tada” repeatedly for 3 second. playRepetitiveSound(soundTada, 300); sleep(3000); Note: Sounds typically need a “Sleep” time to give them time to actually be played.

89 Sound Examples

90 VEX IQ LCD Screen The VEX IQ has a LCD Screen that can be used to display text, number, or shapes/drawings to assist with programming. The VEX IQ LCD has a specific area of the screen that is for the user to draw/write text into. Users can choose to either write to line numbers or directly to x/y coordinates on the LCD screen. Text Line #0 Text Line #1 Text Line #2 Text Line #3 Text Line #4 (0, 47) (127, 47) 48 Vertical Pixels (Y) 128 Horizontal Pixels (X) (0, 0) (127, 0)

91 Display Text to the LCD displayTextLine(lineNumber, “Text”); This command will display a line of text on the VEX IQ LCD Screen. Parameter Description Default Value lineNumber The line number to write to on the VEX IQ LCD. Any previous text on the specified line number will be deleted. Line numbers range from 0-4. N/A “Text” This is the text to be displayed. Because the text displayed is considered to be a ‘string’, it must be surrounded by double quotes. You can display up to 21 characters on a single line.

92 Display Text Example Display the words “Hello World!” to the middle of the VEX IQ LCD Screen. displayTextLine(2, "Hello World!"); sleep(1000); Note: Display commands will need “sleep” time to allow the text to be displayed if the program is not being controlled by a loop.

93 Display Numbers to the LCD
displayTextLine(lineNumber, “Text”, variable); This command will display a line of text and the value of a variable to the VEX IQ LCD Screen. Parameter Description Default Value lineNumber The line number to write to on the VEX IQ LCD. Any previous text on the specified line number will be deleted. Line numbers range from 0-4. N/A “Text” This is the text to be displayed. Because the text displayed is considered to be a ‘string’, it must be surrounded by double quotes. The text can also display “formatting codes” to display values and variables. variable The name of a variable or value – this could be anything that returns a numeric value (sensors, encoders, etc.)

94 Display Text with Numbers Example
A program to constantly update the VEX IQ LCD Screen with the current value from the Gyro Sensor

95 Formatting Strings Formatting Characters:
ROBOTC supports a number of formatting characters for created a formatted string.

96 Other LCD Commands Erases everything in the user’s area of the VEX IQ’s LCD screen. eraseDisplay(); Turn on and off a specific pixel at a specific x/y coordinate. SetPixel(x, y); ClearPixel(x, y);

97 More Display Commands ROBOTC has over 50 different text and drawing commands available for the VEX IQ Take a look at the descriptions/examples of more at the ROBOTC.net Wiki

98 Remote Control

99 Remote Control

100 Remote Control

101 Remote Control

102 Remote Control

103 Remote Control - Names ROBOTC can access all of the data from the VEX IQ Remote Control by referencing the buttons and axes by their described names. Joystick buttons return values of… 1 – Pressed 0 – Not Pressed/Released Joystick Axis return values of… -100 to (0 when centered) ChA ChD ChB ChC BtnEUp BtnEDown BtnFUp BtnFDown BtnRUp BtnRDown BtnLUp BtnLDown

104 Switching Controller Mode
When using the VEX IQ Remote Control, make sure to switch your “Controller Mode” Tele-Op: Requires a Remote Control to be powered on and linked before program will run. Autonomous: No Remote Control required, but program will not read data from the Remote Control Switch this mode from: “Robot Menu - >VEX IQ Controller Mode”

105 Joystick Control – Tank Control
ChA ChD

106 Joystick Control – Arcade Control
ChA ChB

107 Joystick Control – Arm Control
BtnEUp BtnEDown BtnFUp BtnFDown BtnRUp BtnRDown BtnLUp BtnLDown

108 Joystick Control – Get Data
getJoystickValue(joystickChannel) This command will return the current value of a joystick axis (-100 to +100) or joystick button (0 or 1) Parameter Description Default Value joystickChannel The name of the specified joystick component to be accessed. Valid names include: Joystick Axis: ChA, ChB, ChC, ChD Joystick Button: BtnEUp, BtnEDown, BtnFUp, BtnFDown, BtnLUp, BtnLDown, BtnRUp , BtnRDown N/A Returned Value Value returned by the specific Axis or Button. Joystick Axis: -100 to +100 (0 when centered) Joystick Button: 0 (not pressed) or 1 (pressed)

109 Joystick Control - Examples
Simple Joystick Drive Notice how ChA + ChB and ChA – ChB allows the user to turn. For example: If I move my Joystick like this with Arcade Control: ChA = 0 ChB = 50 Thus, the leftMotor = 50 and the rightMotor = -50 As a result, the robot turns.

110 Joystick Control - Examples
Continuous Loop for “Tank Drive”

111 Joystick Conrol--Examples
Adding Buttons—Control the Arm

112 Joystick Control--Examples
Adding Buttons—Control the Claw

113 Joystick Control--Advanced
What can we do to utilize all of the buttons on the Remote Control? What are the things that we are going to do repeatedly? How can we address those things to make our use of the Remote Control more efficient?


Download ppt "Wednesday Program Flow"

Similar presentations


Ads by Google