Upload
gervais-taylor
View
219
Download
2
Embed Size (px)
Citation preview
WednesdayProgram Flow
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
Compare these two examples
Conditional Loops
• Repeat Forever
• Repeat for a count
Conditional Loop
• Use the repeatUntil command block to make a loop conditional to different sensor input
Program Flow
Watch the videos in the “Loops” section and complete the Square Dance Mini Challenge.
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?
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.
If/Else conditional block
If the condition is true, the program will run the If branch In this case, turn right
If/Else conditional block
If the condition is NOT true, the program will run the else branch. In this case, move forward
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.
Program Flow
• Watch the videos under If Else conditional block. When done, we will do the color sensor comparison
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
Repeated Decisions
Why will this code not work?
Repeated Decisions
Why will this code not work?
Repeated Decisions
Repeated Decisions
Program Flow—Line Tracking
• Everyone’s favorite activity—we’ve gone from this:
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
ThursdayFull ROBOTC
NOTE: These slides beyond this point have not been modified for
VEX IQ specifically…
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 ;
ROBOTC Rules/Syntax• Paired Punctuation
– 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…
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.
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
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.
Moving Motors
Moving Motors
Moving Motors
• We can move forward and backwards, go ahead and explore the commands and make the robot turn.
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.
Moving Distances• Timing?
– 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!”
Moving Distances
Notice that we have to reset the encoders
Moving Distances
Notice I do not need to include a command to reset the encoders
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.
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.
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
Code—Robo 500 with Gyro
Variables• What is a variable?– 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.
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• As sign the variable a value (optional, but recommended)
– Example:• int myVariable = 1000;• Type: Integer• Name: myVariable• Value: 1000
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 -32768 to +32767
– Long Integer (long) – Memory Usage: 32 bits / 4 bytes• Integer Numbers Only• Ranges in value from -2147483648 to +2147483647
– Floating Point (float) – Memory Usage: 32 bits / 4 bytes• Integer or Decimal Numbers• Variable precision, maximum of 4 digits after decimal
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 • Integer Numbers Only• Ranges in value from 0 to +255
– Boolean Value (bool) – Memory Usage 4 bits / .5 bytes• True (1) or False (0) values only.
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)
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
Variables
• Some additional notes– Variable’s names must follow a specific rules:
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;
Using Variables
VS.
Repeating Code…
• Copy and pasting only works so well.
• What if we could make each behavior one line of code?
Functions• What is a function?– 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.
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.
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”.
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”
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…
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.
Functions and VariablesVariables 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!
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.
Other Function TypesInstead 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.
Other Function Types
Other Function Types
Creating a Function Library
• Make sure you save in the same place• Suppress warnings for unused functions– #pragma systemFile
Global Variables Debugger
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!
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.
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.
Constant Variables
• Examples:
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)
Variable Locations• In this example, “test2” is not known outside
of the “if” statement block.
Arithmetic Operators
• ROBOTC accepts a number of arithmetic operators:
• Modulo (remainder): a % b• Increment: ++x, x++• Decrement: −−x, x−−• Unary Positive: +x• Unary Negative (inverse): −x
• Assignment: a = b• Addition: a + b• Subtraction: a – b• Multiplication: a * b• Division: a / b
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.
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
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
Logical Truth Tables
NOT (!)
AND (&&) OR (||)
If/Else Statements
• If the “while(true)” loop was missing, this code would only execute the “if” or “else” section once.
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
“else if” ShorthandMake your code more readable by using
the “else if(condition)” command
If/else Shorthand
• You can also have a single line “if” statement with out the need for curly braces “{“
For Loops
• “For Loops” are important for repeating a block of a code a certain number of times.
• For loops require a specific structure:
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
For Loops
Drive and Turn – Loops 10 Times
For Loop Walkthough1. Create the for loop initial
variable2. Check the condition of the
for loop– If true, continue onward– If false, skip the “for” loop
3. Run code inside of “for” loop4. Run the iteration code and
increment “i” by one.• Loop steps 2-4 until 2 returns
false.
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.
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
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.
FridayRemote Control, LCD, Sound
Playing Sounds• 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
Playing a Sound EffectplaySound(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 / soundWrongWayssoundGasFillup / soundHeadlightsOn / soundHeadlightsOffsoundTollBooth / soundCarAlarm2 / soundTadasoundGarageDoorClose / soundRatchet / soundAirWrenchsoundSiren4 / soundRatchet4 / soundCarAlarm4soundPowerOff2
N/A
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.
Playing a Sound Effect RepeatedlyplayRepetitiveSound(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)
N/A
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.
Sound Examples
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 #0Text Line #1Text Line #2Text Line #3Text Line #4
128 Horizontal Pixels (X)48 Vertical Pixels (Y)
(0, 0)
(0, 47) (127, 47)
(127, 0)
Display Text to the LCDdisplayTextLine(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.
N/A
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.
Display Numbers to the LCDdisplayTextLine(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.
N/A
variable The name of a variable or value – this could be anything that returns a numeric value (sensors, encoders, etc.)
N/A
Display Text with Numbers Example
• A program to constantly update the VEX IQ LCD Screen with the current value from the Gyro Sensor
Formatting Strings
• Formatting Characters:– ROBOTC supports a number of formatting
characters for created a formatted string.
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);
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– http://www.robotc.net/wiki
Remote Control
Remote Control
Remote Control
Remote Control
Remote Control
Remote Control - Names
ChD
ChC
ChA
ChB
BtnEUpBtnEDown
BtnFUpBtnFDown
BtnRUpBtnRDown
BtnLUpBtnLDown
• 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 +100
(0 when centered)
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”
Joystick Control – Tank Control
ChA ChD
Joystick Control – Arcade Control
ChA
ChB
Joystick Control – Arm Control
BtnEUpBtnEDown
BtnFUpBtnFDown
BtnRUpBtnRDown
BtnLUpBtnLDown
Joystick Control – Get DatagetJoystickValue(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, ChDJoystick 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)
N/A
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.
Joystick Control - Examples
• Continuous Loop for “Tank Drive”
Joystick Conrol--Examples
• Adding Buttons—Control the Arm
Joystick Control--Examples
• Adding Buttons—Control the Claw
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?