©2002 INSciTE 1 FLL Programming 101 ROBOLAB ™ Sept. 25, 2002 Version 0.6.0
©2002 INSciTE1
FLL Programming 101ROBOLAB™
Sept. 25, 2002Version 0.6.0
©2002 INSciTE2
Legal Stuff• © 2002 INSciTE in agreement with, and permission from FIRST and the LEGO Group.
This document is developed by INSciTE and is not an official FLL document fromFIRST and the LEGO Group. This document may be freely copied and distributed,electronically or otherwise, in its entirety only, and only if used in conjunction withFIRST LEGO® League. Any use, reproduction, or duplication of this manual forpurposes other than directly related to FIRST LEGO League is strictly prohibitedwithout specific written permission from INSciTE.
• LEGO, ROBOLAB, and MINDSTORMS are trademarks of the LEGO Group usedhere with special permission. FIRST LEGO League is a trademark owned by FIRST(For Inspiration and Recognition of Science and Technology) and the LEGO Groupused here with special permission. INSciTE is a trademark of Innovations inScience and Technology Education.
INSciTEPO Box 41221
Plymouth, MN 55441
www.hightechkids.org
©2002 INSciTE3
Credits
This presentation was developed by Fred Rose. Theaccompanying labs were originally done in RCX Code byJoel Stone and converted to ROBOLAB by Doug Frevert. Aportion of the material is taken from “Building LEGO Robotsfor FIRST LEGO League” by Dean Hystad. Amy Harrisdefined the 10 programming steps. Eric Engstrom, JenReichow, and Ted Cochran reviewed ongoing drafts. Erictaught the first class and helped modify the contentaccordingly. Doug modified it based on his ROBOLAB classexperiences.
©2002 INSciTE4
Computer Programming 101• Objective
– Develop a basic approach to, and understanding of,programming the RCX
• Structure– Theory– Examples specific to language– Hands-on
• What this class is– Teach an approach to programming
• What this class is not– Exhaustive reference on every language command
©2002 INSciTE5
Class Agenda
• Computer basics• Programming environment• Simple commands• Subroutines• Sensors• Repetitive statements• Putting it altogether• Advanced topics
©2002 INSciTE6
Format of Each Section
• Theory• Language Specific Commands
– ROBOLAB or RCX Code
• Examples• Debugging• Frequently Encountered Situations• Tips and Tricks
©2002 INSciTE7
The Basics
©2002 INSciTE8
The Computer (Generic)
• Processor executes commands.• Memory stores program and data.• Input devices transfer information from outside world
into computer.• Output devices are vice versa.
Memory
Processor
Inputs Outputs
©2002 INSciTE9
RCX basics
Processor: Hitachi H8 8 bit microcontroller running at 5 to 20Mhz
Memory: 32K of RAM
3 Motor Outputs(A, B, C)
3 Sensor Inputs(1, 2, 3)
Select program (1-5)
Start/Stop selectedprogram
On/Off switch
View to select display
LCD Display:
Motor status, sensorvalues, programstatus
Infrared (IR)communications port
©2002 INSciTE10
Firmware on the RCXSoftware
Your PC
Firmware
Your RCX
Bytecodes{SetPower(A,C,8)}
RAM (RandomAccess Memory) ** RAM loses its datawith no power! Carefulchanging batteries!!
Your Programs
ROM (read only memory)
For FLL purposes, think of firmware as the operatingsystem (like Windows XP or Max OSX) for the RCX
Download
Firmware Setup
Processor (Hitachi)
©2002 INSciTE11
Firmware Loaded?
• Firmware must be installed onto your RCX so thatyou can program the RCX brick.
• Only required to be loaded– When the RCX is new,– Has lost it’s firmware for some reason (such as changing
batteries too slowly),– Or RCX starts behaving badly.
No firmware Firmware loaded.
©2002 INSciTE12
From: Structure and Interpretation of Computer Programs, Abelson, Sussman, and Sussman,
Computer Programs
• A model of a real or mental process.• Are intricate in detail, and
usually only partially understood.• Are rarely modeled to our satisfaction• Thus, programs continually evolve
• The computer is a harsh taskmaster, its programsmust be correct and things must be accurate in everydetail.
©2002 INSciTE13
Writing a Computer Program
• Specify the task– Inputs to be supplied– Outputs to be produced
• Devise an algorithm• Express the algorithm in a computer language
From: Introduction to Pascal, Welsh and Elder,
©2002 INSciTE14
Writing a Computer Program
• Specify the task the computer is to carry out– Move forward 5 seconds– Inputs: Time, power, direction {In an RCX some “inputs” are
set in the program}– Outputs: Motor drive
• Devise an algorithm, or sequence of steps,– Class example
• Express the algorithm as a program in a computerlanguage– Class example
©2002 INSciTE15
Running a computer program (RCX)Write program
on PC(RCX Code or
Robolab)
Downloadto theRCX
RCXexecutes
commands
Program conv.to bytecodes
(textdescription)
Bytecodesconverted toHitachi (RCX)machine code
commands
Move X to register 0011000111...
SetPower(A,3)
©2002 INSciTE16
Tips and Tricks (1)
• The RCX has 5 program slots– Slots 1 and 2 are locked. Unlocked in Administration.– Later we’ll show how to use a touch sensor to get you more
slots (virtually)
• You can also change the time delay before the RCXauto powers down.
• Shielding IR port– The IR tower has a significant range, be careful in an
environment with downloading going on– Build a shield with LEGO bricks for your RCX during the
competition
©2002 INSciTE17
Tips and Tricks (2)• Direction of connecting wires
– You can change motor direction by turning the connection tothe RCX 180º.
• Batteries– Change one at a time to reduce chance of losing program.– Rechargeable batteries work fine.– Use a power plug if you can on your RCX– Source of batteries. If you buy alkalines, buy them in bulk from
a store like BatteriesPlus or from Digikey (www.digikey.com)– Properly used, batteries should last awhile
©2002 INSciTE18
The Programming Environment
©2002 INSciTE19
Language Choices• In FLL, you have two choices for computer language
– RCX Code (also called RIS - Robotics Invention System).• Comes with the commercial version of LEGO Mindstorms
• Only runs on a PC
• Use Version 2.0 if at all possible
– ROBOLAB• Runs on MAC or PC.
• Built on a commercial engineering program called Labview.
• At the FLL level, there is no advantage to either one(we’ve been tracking this for 3 years). RCX Code iseasier to learn but ROBOLAB has more growth potential.
• For FLL at the High School level, no languagerestrictions.
©2002 INSciTE20
Settings (RCX Code)
The “RCX Settings” menu options should be set as shown.RCX IR Power Setting LowRCX Programs 1 & 2 UnlockedRCX Powerdown Time 15 minutes (5 min. to save batteries, 30 min. to lower aggravation)RCX Battery Level should be about 9 voltsRCX Firmware Version 03.01/03.09 (RoboLab 2.0) 03.01/03.28 (RoboLab 2.5)
Administrator RCX Settings
©2002 INSciTE21
The Programming Environment
Double click onInventor4
©2002 INSciTE22
Work Space
Remember to use Context Sensitive Help!
PanelWindow
DiagramWindow
Toolbox FunctionsWindow
Programgoes here
©2002 INSciTE23
Simple Commands
©2002 INSciTE24
Simple Commands
• Simple commands are basic actions– Like English statements
• Turn motor on
• Stop motor
• Reverse motor direction
• Setting parameter values– Many commands have parameters that can be set
• Motor power
• Time
©2002 INSciTE25
Simple Commands
Turn On Motor A -Forward
Turn On Motor A -Reverse
Flip Direction ofMotors
Turn On Motor B -Forward
Turn On Motor B -Forward
Wait for 4 seconds
©2002 INSciTE26
Simple Commands with Parameters
Wait for 25 Seconds Turn On Motor AForward Direction,Power Level 5
©2002 INSciTE27
Motors
• Making the motors move and do something is thepoint (the output) of your program. That’s whatmakes your creation a robot!
• Formally called the 9 volt geared motor– Without load, motor shaft turns at about 350 rpm– With typical robots the power usage should allow 3-4 hours of
use on a set of batteries
• FLL currently allows up to 3 motors on your robot
©2002 INSciTE28
Motor Details
• Motor can be set to different power settings– 5 settings in ROBOLAB– 8 settings in RCX code– Changing power settings is usually a poor substitute for
gearing
• Turning the power setting up higher essentiallymakes the shaft turn faster
4 Studs
3.6 Studs or3 Bricks
2.8 Studs or2.33 Bricks
©2002 INSciTE29
Turning the Motor On
Turn On Motor AForwardFull Power Turn On Motor A
Forward DirectionPower Level 3
Motor direction can also be reversed by reversingthe connector on the RCX. Useful during earlystages of design.
©2002 INSciTE30
Turning the Motor Off
Turn OnMotor A -Forward, onat FullPower
Wait for 2seconds
Stop Motor A
Motors run until stopped!
©2002 INSciTE31
Lab One
Task:Move forward for 5 seconds and return
Then try: Move forward for 5 seconds, turn right 90º
©2002 INSciTE32
Problem Solving andProgramming Process
©2002 INSciTE33
Generic Problem Solving Process
• What’s the problem?• Brainstorm solutions• Evaluate solutions• Try (implement) best solution• Evaluate results
• In our current discussion, the solution is expressedas an algorithm, then converted to a computerprogram
©2002 INSciTE34From: http://whatis.techtarget.com/
What’s an Algorithm?
• The term algorithm (pronounced AL-go-rith-um) is aprocedure or formula for solving a problem. The wordderives from the name of the mathematician,Mohammed ibn-Musa Al-Khowarizmi, who was partof the royal court in Baghdad and who lived fromabout 780 to 850. Al-Khowarizmi's work is the likelysource for the word algebra as well
• A computer program can be viewed as an elaboratealgorithm. In mathematics and computer science, analgorithm usually means a small procedure thatsolves a recurrent problem
©2002 INSciTE35
An Algorithm isLike a Recipe
8 slices of bread
2 eggs
1 cup milk
1/4 cup flour
fat or butter
powdered sugar
Mix together eggs, milk and flour and pass througha strainer. Dip slices of bread into the mixtureand fry in the fat or butter on both sides in afrying pan. Before serving, sprinkle withpowdered sugar
Recipe for French Toast
How can we make this more “algorithm-like”?
Count eggs, mix eggs, for every 2 eggs add 1 cup milkand 1/4 cup flour, and pass through a strainer. Forevery 2 eggs, dip 8 slices of bread….
©2002 INSciTE36
Ways to Express Algorithms
• In the real programming world there are many waysto do this
• In the FLL world, probably the two best ways are:– Draw block diagrams– Literally act it out
• Always talk it out and test it using a team member towalk through it acting like the robot.– Keep actions at lowest possible level
• Go Forward 3 steps
• Stop
• Turn right 90º
©2002 INSciTE37
FLL Ace Programmer in 5 Steps
• Map the generic problem solving process toprogramming
• Create a map of where the robot goes and what itdoes
• Write what the program should do (your algorithm).• Code it• Test, and fix, little pieces at a time
We’ll be adding to this process as theclass progresses
©2002 INSciTE38
Example Algorithm
• Set direction and power of motors• Turn motors on and start timing• Wait 5 seconds,• Stop motors, turn right.
– Turn right by reversing right-side motor– Turn motors on for ? Seconds.
• Stop all motors
Make robot go forward 5 seconds and then turn right 90º
©2002 INSciTE39
Conversion to a Program• Set direction of motors• Start motors• Wait 5 seconds• Set direction/power of motors• Wait ? Seconds• Stop Motors
©2002 INSciTE40
Debugging and Analysis
• Literally walk through it• Ask lots of questions
– What ifs
• Do little pieces at a time– For example, get the robot to where it needs to be first, then
work on getting it to do something
• Use pieces that you know already work– For example, you know how to turn 90°
• Feel confident in your algorithm before starting tocode it.
©2002 INSciTE41
Tricks and Tips• Don’t try to knock off too much at once
– Stick to one or two missions
• Remember to KISS (Keep It Simple)• Develop a little library of algorithms and programs
you know work with your robot.– Going straight, turning, etc.
• Keep things modular (divide task into useful pieces)– This helps a great deal when debugging
• It’s faster fixing problems at the algorithm level thancoding something and seeing what happens
• Give programs descriptive names– Mission1V2 not Amy3
©2002 INSciTE42
Frequently EncounteredSituations (FES)
• You are really not sure which solution is better– Try them both, or at least the primary element of each– Which is easiest for your team to do?
• You can’t think of all the steps needed for thealgorithm– Get out your robot, and walk through it.
©2002 INSciTE43
Subroutines and Comments
©2002 INSciTE44
Subroutines
• Many times in your programming you will want to dosimilar things– Turning 90º Left– Moving an arm to do something
• A subroutine is a small piece of a program that youcan reuse and insert in your bigger program as asingle command– Also called macros, sub vi, functions
• Subroutines are a very important aspect of a good,structured program– Allows you to create a small program fragment that works and
reuse it without thinking about its details
©2002 INSciTE45
Subroutine Use
• If you have a motion or action you can do reliably,and will use a lot, that’s a good candidate for asubroutine.
• It’s easier in an algorithm for a solving a mission tothink “Turn left here at 90º” than always repeat theset of commands you need to do that.
• Another key part of a subroutine is “Modularity”. Itallows you to isolate in one place the code forturning.– See next slide for example
©2002 INSciTE46
Modular Advantages
Start motors
Go straight10”
Turn Left 90º
Go Straight 3.5”
Turn Left 90º
Turn Left 90ºDump barrels
Algorithm - Mission 1
Subroutine
Start motors
Go straight10”
Turn Left 85º
Go Straight 3.5”
Turn Left 85º
Dump barrels85º
Algorithm Updated-Mission 1
If in the process oftesting your program,you realize it is an 85ºturn, you only have tochange your programin one place, in yoursubroutine.
©2002 INSciTE47
Subroutine Commands (local)Call Subroutine #1Define Subroutine #1
Ending Red Light for eachsubroutine definition
©2002 INSciTE48
Subroutine Names
• Useful and informative names.• Suggest using “action + to + target”, but this can be
varied. Some examples:– Fwd2Wall or ForwardToWall or Forward_To_Wall– Fwd2Line, etc.– FwdDist– TurnRight
©2002 INSciTE49
Comments
• Comments are notes in your program explaining whatand why something is being done
• Very important, as the program writer quickly forgetswhy something is done in a certain way
• In a team process like FLL, comments are especiallyimportant as more than one person will be working onthe program.
Enter commentswith the text tool
©2002 INSciTE50
Comment Use
• Add things like who made changes, how batterypower affects change, etc.
• Use color to highlight things
©2002 INSciTE51
Debugging and analysis
• Make sure your subroutine code works well beforemaking it a subroutine!
• Always check the RCX to see which program slot isselected before each download!!
• Remember: Use subroutines to hide complexity anduse comments liberally.
©2002 INSciTE52
Lab Two
Task:Make the program from Lab One into a subroutine
©2002 INSciTE53
Data Input
Sensors
©2002 INSciTE54
Sensors
• Sensors allow your robot to detect the real world.They are inputs.
• Touch– Has your robot made contact with something?
• Light– Is the surface light or dark?
• Rotation– How many times has an axle turned?
• Timer– Internal sensor, keeps track of time
©2002 INSciTE55
Sensor #1: Touch
• Allows robot to detect touching or bumping intosomething
• Good for detecting robot arm movementsThe sensor is activated when the arm moves farenough to push in the touch sensor.
©2002 INSciTE56
Touch Sensor WaitFor Commands
Wait for push in(default 1 click onport 1)
Wait for let go(default port 1)
Wait for5 clickson port 2
Wait for let goon port 3
©2002 INSciTE57
Touch Sensor Fork Commands• Waiting for a touch sensor to be pushed or released
can be useful, but many times you want to dodifferent things based on the value (is it pushed in orout?)
• If touch sensor released, turn on motor A• If touch sensor pushed in, turn on motor B
Fork MergeFork
©2002 INSciTE58
Touch Sensor Loop Commands• Loop until a touch sensor is released. Useful if the
loop contains other sensor functions that must bemonitored repeatedly. For instance, a routine thatfollows a wall until the front bumper hits something.
This marks the endof the loop. Every
loop must have one.
©2002 INSciTE59
Push In, Clicks and Let Go TouchesTwo additional functions involving the Touch Sensor:• Click Counter: a counter of PushIn/LetGo cycles.• Touch and Release Counter: count changes (twice
as big as the click count).
Loops:
Forks:
Push In Let Go
Pushed?
Push InLet GoCount
ClickCount End
©2002 INSciTE60
Sensor #2: Light
• A light sensor detects reflected light from its red lightemitting diode.
• Light sensors operate in "percent" mode, anywherefrom 0 to 100 in value.– Higher the number, the brighter the light, hence the lighter the
surface the more light is reflected back
• Light sensor can be the most useful and the mostfrustrating sensor
©2002 INSciTE61
Light Sensor Readings
• Lowest reading likely 20% (in very dark room)• Highest reading likely 100% (pointing at a bright light)• Normally between 30-60%• Readings also depend on the color of the surface
– See “Building LEGO Robots for FIRST LEGO League” byHystad for extensive discussion of this
– Results vary. You should experiment with yoursurfaces/colors
• Light sensor is extremely sensitive to the distance between thesensor and the reflecting surface. Even small variations canmake the readings unusable. Try to keep the sensor close tothe surface and shielded.
©2002 INSciTE62
Light Sensor Readings
• The light sensor averages its readings over roughly acircular area. Don’t drive too fast or you will getinaccurate readings
• It is very sensitive to ambient light. Shield thesensor as much as possible and try it out under theconditions that you will compete in. Test it oncompetition day.
50%
30%40% 35%
45%
30%35% 40% 45%
50%
©2002 INSciTE63
Light Sensor WaitFor Commands
Wait for Light(greater than 45)
Wait for Brighter(increase by 10)
Also Wait for Darkand Wait for Darkercommands
©2002 INSciTE64
Fork Commands (Light)
• If light sensor greater than 45, turn motor A on in forwarddirection
• If light sensor less than or equal to 45, turn motor B on inforward direction
• The light sensor fork is very useful.
©2002 INSciTE65
Calibrate Light Sensor
• This program assumes you physically move the robotover the light and dark areas, and then use a touchsensor to trigger a reading.
• The containers Red and Blue now contain thecalibrated values of light and dark. These containerscan be used elsewhere in your program.
Position light sensor over white areaand push touch sensor to take a reading
Set container Red to this value
Position light sensor over dark area andpush touch sensor to take a reading
Set container Blue to this value
©2002 INSciTE66
Refining the Calibration for Edge Following
The example set the thresholds at the white and black.This example sets them at light and dark grey.
©2002 INSciTE67
Sensor #3: Rotation
• The rotation sensor is used to measure how far arotating axle has turned. As the axle turns, a counterin the RCX is incremented or decremented.
• Each full rotation registers as 16 counts giving thesensor a resolution of 22.5 degrees (360/16). Henceit is sometimes called the angle sensor.
2 studs
4 studs
2 bricksor2.4 studs
3.5 studs
1.33 bricksor1.6 studs
©2002 INSciTE68
Rotation WaitFor Commands
Wait for Rotation Absolute(count greater than 64 or 4complete rotations withoutreset). That means it doesnot reset to zero.
Wait for Rotationcounter greater than 50or 3 1/8 (50/16)rotations.
©2002 INSciTE69
Fork Command (Rotation)
• If rotation sensor greater than 64 (4 complete axlerotations), turn motor A on in forward direction
• If rotation sensor less than or equal to 64 , turn motor Bon in forward direction
©2002 INSciTE70
Using the Rotation Sensor
• Use as an odometer (how far have you gone) oras an angle sensor (where does the arm point)
• Turn motors on to go straight– Wait until eight complete rotations– {How far is eight rotations? See next slide}
• Because of momentum, a robot travels beyond therotation sensor’s stopping point. Read the sensoragain to find out where the robot stopped.
• Measure rotations: Load a program does nothing butfloat the motors and has any rotation sensor function.Run. The LCD view shows rotation value.
©2002 INSciTE71
Calculating Distance• The rotation sensor also brings in the possibility of
doing some real math!
• We’ll leave that as an exercise for the reader!• Of course, trial and error also works.• Sources of error in calculation - dirt on surface, using
a skid rather than a wheel, backlash (poor fittinggears)
Circumference
Diameter 1 Revolution
Circumference = pi x Diameter
©2002 INSciTE72
More on Rotation Sensor
• Rotation sensor can count forwards or back, up toAbsolute Value (32,767), then it rolls over to largestnegative from largest positive (or vice versa),however this is really unlikely to occur in FLL.
• Increase sensor resolution with gear reduction• Rotation sensor is quite reliable if shaft speeds are
kept in 60-1000 rpm range, some counting problemsmay occur at very high or very slow speeds.– Motors typically around 200 rpm.
©2002 INSciTE73
Debugging and Analysis
• Common sources of repeatability problems for therotation sensor– Programming: forgetting to reset the sensor before use.– Design: inadequate sensor resolution (trying to measure
something very accurately without using gear reduction)– Control: accelerating and turning too fast– Variations in the initial conditions: not putting everything in
the right place,or at least the same place, before pushing therun button.
©2002 INSciTE74
Sensor #4: Timer
• Wait until Blue Timerreaches 5 seconds– Time in tenths of a second– Blue timer must be zeroed before
it’s used– ROBOLAB has 3 timers, blue, red,
yellow
• Zero Blue Timer (reset)
©2002 INSciTE75
Tricks and Tips• Use a touch sensor to get more program slots
– If touch sensor is in, execute one fork branch– If touch sensor is out, execute the other fork branch– Do this for every program slot, and you end up with 10
program slots instead of 5.– Add a brick to robot between missions to push the touch
sensor in, to achieve this.
• Use a light sensor to achieve rotation counting– Aim light sensor at a piece of your robot that rotates and
measure color differences (for example, have two colors on apiece that rotates), and count these.
– Clockwise or Counterclockwise? Does it matter?– Touch sensors can also mimic rotation sensors.
©2002 INSciTE76
Stacking Sensor Ports
• Attaching multiple sensors to the same port• Allows you to use more than 3 sensors• Touch sensors work best for this, rotation sensors
cannot be stacked.
Out In White BlackOut 0 1 ~50 ~35In 1 1 100 100
White ~50 100 ~75 ~70Black ~35 100 ~66 ~60
Sensor 1
Sens
or 2
Stacked Sensor values Touch Light
Touch
Light
©2002 INSciTE77
Lab Three
Task:Move forward for 50 rotations, turn right 90º
orExperiment with other sensors
©2002 INSciTE78
Variables and RepetitiveCommands
Controlling looping, doing things over andover, and adding structure
©2002 INSciTE79
What’s a Variable?
• A value that you can change during your program– This value is “variable”, hence the name
• For example, the value of a light sensor may bemeasured during the program and placed in avariable called RED.
• Think of a variable as a container containing thevalue of something.– In ROBOLAB, variables are called containers
• Useful in subroutines to pass in parameters– For example go straight N seconds where N is a variable.
©2002 INSciTE80
Defining a Container
• On the Functions pallet, thecontainer menu has manychoices. All of these fill acontainer with a value.
• There are 21 containers.3 are predefined containers:Red, Blue, and Yellow. Use amodifier to identify the rest(numbers 3-20).
©2002 INSciTE81
Use of a Container
• Instead of “hardcoding” 50 (above),fill a container with “50”, then get the container (below).
• Once set, containers hold their values (unless thefirmware fails.) Fill in Program #1, get in Program #2.
Set the redcontainer to 50.
Get the value ofthe red container.
©2002 INSciTE82
Structures
• In creating an algorithm, many times you want to dosomething like “As long as the light sensor reads adark value, keep going straight”.
• Structures (or repetitive commands, loops, controlstatements, while commands) are used for thispurpose
• These commands allow the repetition of somecommand, or group of commands, until somecondition is met.
• There are always multiple ways to do these, thissection will cover some examples.
©2002 INSciTE83
Structures
• Split Task– Make 2 parallel program tasks
• Subroutines– Declare, then call a local subroutine
• Forks– Either this way, or that
(If, then, else)
• Jumps– Jump to another spot in program
(GoTo)
• Loops– Repeat until something happens
(While Do or For Next)
©2002 INSciTE84
Split Task
• Make two tasks• Start motors A and B• Wait for 2 sec, or until touch sensor on port 1 is
pushed in, whichever comes first, then stop motor B.
Create a new task to runsimultaneously
©2002 INSciTE85
Jumps
• Jumps can form infinite loops.• Multiple jumps (like red above) are allowed, but only one “Land”.• ROBOLAB has a variety of jump colors/numbers to allow
multiple jumps in your program• Jumps are a simple control structure.• Warning: Multiple jumps are difficult to debug.
Jump from hereto “Land” here
Music never plays!
Useless, but not harmful
©2002 INSciTE86
Loops
• Loops are a powerful and useful control structure– In other programming languages:
For … Next Do loop n timesWhile … Do Repeat until some test is false
• There are loops for every sensor to allow you tocontinually do a command or sequence of commandsuntil a sensor condition changes– Extremely useful for navigation, moving an arm, etc.
• If your algorithm says something like: “While thesensor reads x, keep doing this”, then this is a placefor a loop.
©2002 INSciTE87
Loops Palette
• Play music while thetouch sensor isreleased.
• Additional commandscan be put in the loop.
©2002 INSciTE88
Simple Loop
• Convert this setof commands
• to somethingsimpler usingloops
©2002 INSciTE89
More Complex Use of StructuresFollow lines (based on light sensor thresholds pg 65).
IF over edge to white, THEN turn left until over edge to dark.
This results in a zig-zag motion along the line edge.
ELSE (not over edge to white) IF over edge to dark, THEN
turn right until over edge to white, ELSE go straight.
©2002 INSciTE90
Comparing Algorithms
• Compare the previous line follower to this one:
• Better– Simpler. Doesn’t assume motors are running.
• Worse– Motors only run one at a time.
©2002 INSciTE91
Comparing Sensor Commands
You can generally make your algorithm fit the commandyou want to use.
• Loop– Execute something until an event
• WaitFor– Wait for an event, then execute something
• Forks– Make a choice based on a sensor value at a given point in time.– Be careful to make sure you will be watching for the event at the
right time
©2002 INSciTE92
Tricks and Tips
• Never wait for a sensor to be an exact value, alwaysgreater than or less than– You could miss the event due to sampling rate– For example, wait until rotation greater than 64 not equal to 64.
©2002 INSciTE93
Lab Four
Task:Move exactly one lap around an oval.
(Black 2cm line on white paper)
©2002 INSciTE94
Advanced TopicsEvents
Debugging ToolsAdditional Resources
©2002 INSciTE95
Events
A programming style used to handle situations whereany one, of many things, can happen. It is mostuseful when more than two sensors are beingwatched at the same time.
An event is:• The moment something happens.• It’s also the setup. Knowing what to watch, when,
and where.• And it’s what to do after the event happened.
©2002 INSciTE96
Events (the logic)
• Coding an Event– The setup: declare the sensor to watch, the port, the threshold
that triggers the event.– Start watching– Event Landing
• All events land in the same place. (ROBOLAB)
• Determine which event triggered and react.
• May continue on or restart event watching.
• Events could be recoded– Events could be coded as infinite loops containing sensor
forks and jumps that land outside the infinite loop.
©2002 INSciTE97
Events Using Forks
Here is an example that watches 3 sensors using forks.
©2002 INSciTE98
Events
ROBOLAB 2.5 introduced event functions.
©2002 INSciTE99
Events (Hysteresis)
Hysteresis – a lagging between the time a force has aneffect and the time it makes a change.The word was created to describe the process inmagnetic regions (like magnetic tape) that allowsthem to be changed, but then resist change.Not related to the word “hysterical”, but often thoughtof as the behavior of sensors near their thresholdvalue.
In robotics, a resistance to change factor added tosensor values so they don’t behave “hysterically”.
©2002 INSciTE100
Debugging Tools
• Music– ROBOLAB has several functions that play notes on the RCX.
• Use them to identify sections of code.
• Identify the end of the task, subprogram, or program.
– It helps to make the notes quick. A good ear can hear thedifference between C, E, and G, otherwise use two notes.
• LCD– ROBOLAB 2.5 introduced a function
to write to the RCX’s LCD panel.
• RCX Interrogator– From your PC (or MAC), use the interrogator to view the values
of containers and sensors.
©2002 INSciTE101
Additional Resources
• Internet:– www.hightechkids.org/fll/coaching (this presentation)– www.lugnet.org– www.crynwr.com/lego-robotics/ (firmware decoded)– www.ni.com (LabVIEW™)
©2002 INSciTE102
Putting it All Together
How to Become an FLL Ace Programmer in10 Easy Steps
©2002 INSciTE103
FLL Ace Programmer in 10 Steps1. Create a map of where the robot goes and what it
does. These are your Requirements.2. Use the Requirements to further examine the
problem– What tasks can go in the same program?– Any actions we do in multiple places? (good candidates for
subroutines)– Will using variables help?
3. Write out your algorithm4. Think about how it could fail. How can you recover?
– For example, the robot hits a wall it shouldn’t have. What canyou do to allow it to recover?
©2002 INSciTE104
5. How are you going to test and debug it?– Perhaps use a series of beeps in the program to tell you where
the program is.
6. Have a system for versions.– Put comments at the beginning of the program– Always save a working version in a file with a name that
makes sense (like date, etc.).
7. Write the code using above information
FLL Ace Programmer in 10 Steps
©2002 INSciTE105
7. Write the code using above information– Code little parts and test them– Name subroutines and files with descriptive names
(Right_90_Deg_turn is better than Rturn)– Think about how readable the code is. This makes it less
confusing.– Use a lot of comments
FLL Ace Programmer in 10 Steps
©2002 INSciTE106
8. Fix bugs in a stepwise manner– Fix the bug, test it, then test other things related to it to make
sure they weren’t broken by your fix.– 80% of the bugs come from 20% of the code.
9. Don’t be afraid to scrap everything and start over ifthings are getting complex and fragile.
10. If coding/testing/bug fixing is driving you insane, gohave an ice cream cone! Take a break, have a friendlook at your code, come back another day.
FLL Ace Programmer in 10 Steps
©2002 INSciTE107
Summary
• Remember the problem solving process• Remember to create the algorithm before writing your
code• Use subroutines to keep things cleaner• Be careful in using sensor commands.• Use comments liberally• Program and test little pieces at a time• Have fun!!