13.07.2015 Views

Programming - VEX Robotics

Programming - VEX Robotics

Programming - VEX Robotics

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

programmingprogrammingtable of contents:what is programming? 8.3getting readysetup overview 8.4installing the easyC programming software 8.7programming hardware setup 8.13download the test code 8.14programming introductionprogramming options 8.19motor and sensor setup 8.20using online code to test your robot 8.21restoring default code 8.22programming sequence 8.23writing your first program 8.24tips for saving programs 8.26autonomous programsprogram two: using the motors 8.27introduction to sensors 8.33using a sensor 8.34understanding bump sensor test code 8.36program three: using motors andsensors together 8.38program four: reversing and turning 8.41remote control programsprogram five: using the radio controltransmitter 8.4501/31/05Inventor’s Guide8 • 1


programmingtable of contents, continued:combining remote control andautonomous programsprogram six: autonomousand remote control 8.47about easyCadditional help 8.50troubleshooting 8.51programming strategies 8.52compilation errors 8.53other errors 8.55challengeskeeping count 8.56headache! 8.57afterword 8.58The MPLAB® C18 C Compiler software is distributed alongwith the <strong>VEX</strong>TM <strong>Robotics</strong> Design System <strong>Programming</strong> Kit underlicense from Microchip Technology Inc.The Microchip Name and Logo, and MPLAB, PIC, and dsPICmarks, are registered trademarks or trademarks of MicrochipTechnology Inc. in the USA and other countries, and are used byInnovation First, Inc. under license.01/31/058 • 2Inventor’s Guide


programmingwhat is programming?Technically, programming is the process of creating asequence of instructions that tell a computational device,such as the Micro Controller on the Vex robot, how toperform a task. However, a programmer’s real task ismuch broader and more involved than simply listinginstructions for the robot to follow.The programmer’s true task is to analyze the problemat hand, and to identify the behaviors that the robot willneed to perform in order to accomplish its task. Theprogrammer must then break those behaviors down intosimpler and simpler parts until they are at the level thatthe robot can understand directly, the level of a singleeasyC icon. The programmer will then organize thoseicons so that each simple behavior runs at the right time,and the desired overall behavior will emerge.3There is, of course, always more than one way to solve aproblem, and it’s up to you, the programmer, to determinewhat approach works best for your situation. By usingyour creative and analytical abilities to the fullest, youcan build and program a robot to conquer any challenge!01/31/05Inventor’s Guide8 • 3


programmingsetup overviewgetting readyThe Vex programming kit is a combination ofsoftware and hardware components that enable you towrite programs for your robot and to then download themonto your Micro Controller.You will program your robot on your computer witheasyC ® , the software included on the <strong>Programming</strong> CDthat comes with the kit.The <strong>Programming</strong> Kit includes both a USB-to-serialcable and a programming module. The USB-to-serialcable is used to convert your USB port into a serialport. The serial end of the cable will then plug intothe programming module, allowing you to downloadprograms from your computer to the Micro Controller.The following assembly pages will step through installingand testing the programming kit hardware and software.For information and an overview of programming forVex, see the programming introduction section.1 Collect and identify the partsfrom the list of materials below:materialsqtyVex <strong>Programming</strong> Kit CD 1USB-to-serial adaptor cable 1robot interface cable 1programming module 101/31/058 • 4 Inventor’s Guide


programminggetting readysetup overview, continuedVex <strong>Programming</strong> Kit CD x 1robot interface cable x 1programming module x 1USB-to-serial adaptor cable x 101/31/05Inventor’s Guide8 • 5


programminggetting readysetup overview, continued2 Follow this recommended sequence to install thesoftware and prepare your robot for programming:1. Install the easyC softwarepackage included on the CD thataccompanies the kit. This includes theeasyC programming software and theUSB-to-Serial cable driver.2. Attach the programming hardwareto the robot. The USB-to-serial cableallows the programming module tointerface with any PC through a standardUSB port. Complete the connectionbetween computer and robot by attachingthe <strong>Programming</strong> Module and the robotinterface cable.3. Download and test code on the robot.Use the provided test program to checkcommunication between the computer andthe robot.01/31/058 • 6 Inventor’s Guide


programminggetting readyinstalling the easyC programming software1 Insert the easyC programming CD into your computer’sCD-ROM drive.2 Your computer should automatically begin installing easyC.You should see the following screen. Click Next.NOTE: If this screen does not appear, you may need tomanually run the installer from the CD. You can do this byopening My Computer from your desktop or Start Menu andfinding your CD-ROM drive. You can manually click the folderlabeled “Install”, then click easyC.exe.3 At the License Agreement screen, read the easyC licensing.agreement. If you agree to the listed terms of use, click “Yes.”01/31/05Inventor’s Guide8 • 7


programminggetting readyinstalling the easyC programming software, continued4 If you need to install to a specific directory, or to a driveother than C: drive, press the Browse button to select an installlocation, and then click Next to continue. Otherwise, just clickNext to continue.5 Click Install to begin the installation.01/31/058 • 8 Inventor’s Guide


programminggetting readyinstalling the easyC programming software, continued6 easyC will be installed on your computer. This may take afew minutes.7 When the installation is done, you will see this screen. Check thebox to install USB to serial adaptor driver. If youwould like to add an easyC icon to the desktop, check that box aswell. Click “Finish” to conclude the installation process of easyC.8 The easyC icon should now be accessible from either your desktop(if you checked the box for a desktop icon) or your Start Menu inthe Programs or All Programs area, under “intelitek easyC for Vexcontroller”.01/31/05Inventor’s Guide8 • 9


programminggetting readyinstalling the easyC programming software, continued9 After installing the easyC software, the USB-to-serial cablesoftware installation will start. Click Next.10 The USB-to- serial cable software will be installed on yourcomputer. Click Finish to complete your install.11 Plug the USB-to-Serial cable into into your your computer, you may remove the CD. Keep the CDand Envelope in a safe place. You will need the CDKEY later.01/31/058 • 10 Inventor’s Guide


programminggetting readyinstalling the easyC programming software, continued12 You will need to determine the COM port for your USB-to-Serialcable. To do this you must open the device manager.Single click on the “Start” text in the Windows Desktop.Single click on the “Control Panel” text.The control panel may be in two different views. If it is in the“Category view” click “Performance and Maintenance” and thenclick the “System” text.If the control panel is in “Classic View” simply double click the“System” icon.01/31/05Inventor’s Guide8 • 11


programminggetting readyinstalling the easyC programming software, continuedOnce you are into the “System Properties”, single click on the“Hardware” tab. Single click on the “Device Manager” button.Within the device manger do the following:Double click on the “Ports (COM & LPT)” text. Under Prolific USB-to-Serial Comm Port (COMx) make note of the number “x” as it will beneeded to correctly configure your easyC software.Close the “Device Manager” window.Close the “System Properties” window.Close the “Control Panel” window.01/31/058 • 12 Inventor’s Guide


programmingprogramming hardware setupgetting readyConnect your robot to your computer.Now that the software is installed, you are almost ready to download the<strong>VEX</strong> test code to your robot. However, you still need to attach your <strong>VEX</strong>Micro Controller to your computer using the programming kit hardware.This setup will allow you to download code from your computer to your robot.1. Attach the serial connector of theUSB-to-Serial cable to the programmingmodule.2. Attach the robot interface cableto the programming module.3. Connect the robot interfacecable to the “Serial” port on the<strong>VEX</strong> Micro Controller.01/31/05Inventor’s Guide8 • 13


programminggetting readydownload the test code, continued3 Click “File”, then select “Open Project”.4 Open the folder called “Test Code”. Find the file named“TESTPROGRAM.ECP”. Double-click it.5 Make sure the terminal window will appear by clickingthe “Build and Download” menu and click the“Loader Setup” option.6 The “Loader Setup” configuration window will appear. In thelaunch after download section, select “Terminal Window”.Click OK.01/31/05Inventor’s Guide8 • 15


programminggetting readydownload the test code, continued7 You must now set the COM port using the COM port informationyou found in the installing the USB-to-serial adaptor section. Todo this, open the Terminal window.Now click on the terminal window icon in the toolbar.The terminal window will appear. Within the terminal window, click onthe “Port Setting” menu. In this menu, click on the COM port you foundin the installing the easyC programming section. If you were not able tolocate your COM port, try different COM ports until downloading succeeds.8 We recommend that you update the Master Code for best performanceThe Master Code is responsible for the behind-the-scenes work inside the<strong>VEX</strong> Micro Controller. First, turn your robot on.9 Since you are still in the terminal window, go to “Options” and click“Download Master Code...”.01/31/058 • 16 Inventor’s Guide


programminggetting readydownload the test code, continued10 You will see a confirmation screen appear. Click “Yes”.11 Click on the <strong>VEX</strong> folder, then click on Open.<strong>VEX</strong>11aYou will need to choose which version of the Master Code to use to updateyour <strong>VEX</strong> Micro Controller. Choose the latest Master Code available and click “Open”.<strong>VEX</strong>11bThe computer will begin downloading code to your robot.This may take several minutes.If you see an error message duringcompling or downloading, refer totroubleshooting, page 50 at the endof the programming guide12 The terminal window will appear with the message “Download complete”.You are now ready to download the test program to the robot!01/31/05Inventor’s Guide8 • 17


programminggetting readydownload the test code, continued13 Click the “Build and Download” icon on the menu bar atthe top of the screen.14 You may see a confirmation screen appear. Click “Yes”.Your computer will begin downloading codeto your robot. This may take several minutes.If you see an error message duringcompling or downloading, refer totroubleshooting, page 50 at the endof the programming guide15 The program will begin to run immediately uponfinishing the download. You should see the windowbelow appear and text will begin to display. Theprogram will test each of the motor ports(1 through 8) on your robot.Any motor plugged into the Motor port bank willmove briefly when its port number comes up.If your robot is configured according to the “logic”section of your <strong>VEX</strong> Inventor’s Guide, for example,then you will see motors 2 (right side) and 3(left side) respond when those numbers comeup, because you have motors plugged into thosetwo ports.01/31/058 • 18 Inventor’s Guide


programmingprogramming introductionprogramming optionsTo start you off and give you a safe "home base" to returnto while you explore, a few key programs are alreadyincluded with the easyC software.Code provided for you:Online Code (page 21):This code allows you to control the motors and monitor the sensorvalues on your robot directly from your computer. The Online code isa valuable testing and troubleshooting tool.Default Code (page 22):This code is the default programming for the <strong>VEX</strong> robot (theprogram it came with fresh out of the box). This code is alwaysavailable in case you ever need to return your robot's MicroController programming to its original state and get a fresh start.The instructions on the following pages will show you how toload and use these included programs.When you do begin developing your own robot code, youwill find that your program's behavior will usually followone of three main patterns:Writing your own code:Autonomous Code (page 27):Autonomous code allows a robot to perform behaviors without inputfrom the radio control transmitter.Radio Control Code (page 45):Radio control code allows you to configure the way in which theradio control transmitter controls the robot.Mixed Autonomous and Radio Control Code (page 47):Autonomous code can be integrated with radio control code toachieve even better robot performance for complex tasks.All of the code written in theprogramming guide is compatiblewith the Squarebot design of the<strong>VEX</strong> robot. Although these programsmay be applied to any <strong>VEX</strong> robotdesign, you may have to make smalltweaks (like reversing the direction amotor spins) to get a robot other thanSquarebot to perform the programscorrectly.The instructions and examples on these pages will guide youthrough some basic examples of each type of program behavior.These examples all use the same hardware configuration, foundon page 13. Please take a moment to ensure your robot is setup properly.01/31/05Inventor’s Guide8 • 19


programmingmotor and sensor setupprogramming introductionBefore you begin the programming examples in thissection, please take a moment to ensure your robot’shardware is configured properly. All motor and sensorconfigurations are based on the Squarebot designpresented in the assembly steps for the first six Inventor’sGuide chapters.1Make sure the left motor is plugged intoMotor port 3 of your <strong>VEX</strong> Micro Controller.2 Make sure the right motor is plugged intoMotor port 2 of your <strong>VEX</strong> Micro Controller.NOTE: For instructions on how to attach motors toyour <strong>VEX</strong> Micro Controller, please refer to pages 6and 7 of the “logic” section of your Inventor’s Guide.Front Bump SensorLeft MotorRight Motor3 Check to see that the front-mounted bump sensor is plugged intoAnalog/Digital port 6.4 The rear bump sensor is not used in the following examples.Please make sure the wire will not get caught in your robot'sgears or wheels.01/31/058 • 20Inventor’s Guide


programmingprogramming introductionusing online code to test your robotThis code lets you control the robot’s motors and monitorits sensor inputs directly from your computer. This can bevery helpful in troubleshooting problems with your robotor computer interface. To use the online code, follow thesteps below.1 Make sure your programming hardware is connected correctly(see programming hardware setup, page 13) and your robotis on.2 Start easyC and select “Online Window...” from the“Build and Download” menu.1.Click “Download Online Code”. Thiswill begin a download to your robotimmediately.NOTE: If your download does notcomplete successfully, visit troubleshootingon page 50.2. You are now ready to begin using yourcomputer to control your robot. Adjust theslider bars to make the robot’s motors spinclockwise or counter-clockwise, or not spinat all.If you have set up your robot according tothe motor and sensor setup, then you willadjust slide bars 2 and 3.3. As you slide in either direction, notethat the number indicator changes. Asetting of 0 means that the your robot’smotor(s) will spin fastest counter clockwise(CCW) and a setting of 255 will spinthe motor(s) fastest clockwise (CW).4. The Analog/Digital and Interruptwindows allow you to monitor the statusof the sensors on each input port, or turnthe output ports on or off. Try pressingthe button on the Bumper Sensor and seewhat happens.01/31/05Inventor’s Guide8 • 21


programmingrestoring default codeprogramming introductionShould you ever need or want to restore the defaultfunctionality that your robot came with originally,follow the steps below.1 Make sure your programming hardware is connected correctly(see programming hardware setup, page 13) and your robotis on.2 Select “Download Default Code” from the “Build and Download” menu.3 A confirmation screen will appear. Click “Yes.” The default codewill immediately begin to download to your robot.4 Your robot will now function in its “out-of-box” state.Use the transmitter to operate the robot with its“out-of-the-box” functionality.NOTE: For more information about thebehavior of the default code, refer to thefollowing sections of the Inventor’s Guide:• The Control chapter• Appendix E - Control Configurations01/31/058 • 22Inventor’s Guide


programmingprogramming introductionprogramming sequenceNow that you’ve had some practice downloading and usingthe included programs, it's time to learn to write some ofyour own! These are the three basic steps you will followeach time you create a new program for your robot.1. Write Code 2. Compile & Download 3. TestWrite your program in easyC.Launch easyC and select “NewProject” from the “File” menu.Once you have completedyour code, make sure yourprogramming hardware is setup properly and the robot is on.Then select the “Build & Download”option from the “Build &Download” menu.Run your code! Immediatelyafter download, your robot willstart executing the code. Tore-run the code from thebeginning, switch off your robot,and then switch it back on.A confirmation screen willappear. Click “Yes”.Drag function block iconsinto the program window towrite or edit code.easyC will replace old codeon the robot with new codeIf you receive an errormessage during compile anddownload, please refer to thetroubleshooting section.01/31/05Inventor’s Guide8 • 23


programmingwriting your first programprogramming introductionStart simple. For your first program, you will learn how to turn asingle motor on.1 Launch easyC and select “New Project” from the “File” menu.2 Select “L2” on the toolbar.NOTE: All of the example problems in the“<strong>Programming</strong> Guide” use the “L2” setting.This setting determines what functions areavailable in the “Function Blocks” window.3 In the Function Blocks window (leftmost panel in themain window), under the “Outputs” heading, find the“Motor - Motor Module” block.NOTE: Be sure to dragand drop your icons ontothe line in the programmingwindow between the“Begin” and “End” icons.ConfigGlobalsBEGINVariablesvoid main (void){END}4 Left-click and drag the “Motor - Motor Module” block into theprogram window, between the Begin and End blocks. Release theblock there.5 The motor module configuration window will appear. Make sure“Motor Number” is 3 and “Clockwise” is selected. Click “OK.”01/31/058 • 24Inventor’s Guide


programmingprogramming introductionwriting your first program, continued6 Your program should now look like this:ConfigGlobalsBEGINVariablesENDvoid main (void){SetMotor (3,255);}You are now ready to compile and downloadyour first program!7 Make sure your hardware is set up properly and the robot isturned on. Select the “Build and Download” option in the “Buildand Download” menu. Click “Yes” on download HEX file confirmation.NOTE: If you recieve anyerror messages, pleaserefer to the troubleshootingsection on page 50.8 As soon as your program finishes downloading, the leftmotor will turn on, making your robot spin in place. To make itstop running, switch off the robot.9 Now that your robot is off, you can unplug the wire fromthe serial port on the Vex Micro Controller and place yourrobot somewhere safe (for example, the floor). To run yourprogram again, switch the robot back on.10 Close the IFI/intelitek Loader by clicking on the x .11 Save your program as “intro program one” by followingthe steps on the next page.Congratulations, you have programmedyour robot sucessfully!01/31/05Inventor’s Guide8 • 25


programmingprogramming introductiontips for saving programsIn programming, it is very important to save your programsfrequently. This will allow you to avoid losing work in casesomething goes wrong, and let you store programs at importantmilestones in their development, should you need to return tothem later.To save a project in easyC, select “Save Project” from the “File” menu.The “Save Project As” window will appear.Enter the name you would like to save theprogram as. Be sure to name your programssuch that you can easily tell which programis which as you write more programs.“MazeRunner v3 6-7-05” is a good name;“myprogram” is not.You may save programs to any directory onyour computer, but we recommend using theprojects directory to make it easier to findprograms later.As you write more complex programs you may find it usefulto save multiple versions of the same code, so that you canrevert back to an earlier version if your changes causeundesired behaviors. To save your project under a differentname, select “Save Project As...” from the “File” menu.To Open saved programs Select “Open Project...” from the “File” menu.The “Load Project” window will appear.Find the program you would like toopen, left-click on it, and click “Open”.Loading ProgramsThe four most recent programs you havehad open may also be opened directly inthe “File” menu.To move a program:If you want to move aprogram, say from onecomputer to another, youmust move both the .BCPand .ECP files.01/31/058 • 26Inventor’s Guide


programmingprogram two: using the motorsIn the last section, you learned how to turn on one motor.Now, you will take things one step further by turning onboth motors to make the robot move forward. In thissection, you will write a program to move your robotforward for three seconds.If you recall from the first program, a window withseveral motor control options appeared when you droppedthe Motor Module icon into the program diagram. Here isa more thorough explanation of what all those options do:autonomous programsMotor number - This specifies which motor willbe controlled. This number refers to the motor portnumbers (1-8) on the Vex Micro Controller.With the hardware setup we're using (see page 11),the left motor is motor number 3, because the leftmotor is connected to motor port 3 on the <strong>VEX</strong> MicroController. The right motor is plugged into Port 2, so itwould be motor number 2."Motor Module" configuration window01/31/05Inventor’s Guide8 • 27


programmingautonomous programsprogram two: using the motors, continuedMotor direction - This specifies which direction theselected motor will turn. Clockwise and counterclockwiseare oriented as if you were looking downinto the hole where the motor shaft goes.The User Value option allows you to specify an exactspeed and direction value. See the online code section,page 21, for the meanings of these numbers."Motor Module" configuration windowSquarebot has two motors, one controlling each side ofthe robot. This combination is enough to perform anyof the basic movement functions. The chart at rightdescribes the combination of motor movement needed toperform each maneuver.Looking at the chart, you can see that to get therobot to move forward, you must set the left motor to"Clockwise" and the right motor to "Counter-clockwise".Left MotorClockwiseRight MotorCounter-ClockwiseTo learn more about motors, refer to the MotionSubsystem Chaper of the <strong>VEX</strong> Inventor’s Guide.Counter-ClockwiseClockwiseCounter-ClockwiseCounter-ClockwiseClockwiseClockwise01/31/058 • 28Inventor’s Guide


programmingautonomous programsprogram two: using the motors, continuedNow it’s time to write the program. The goal is to makethe robot move forward for three seconds and then stop.1 Launch easyC and open a "New Project" from thefile menu.2 In the “Function Blocks” window, under the“Outputs” heading, find the “MotorModule” block.ConfigBEGINVariablesvoid main (void){END}3 Left-click and drag a “Motor Module”block into the program window between the“Begin” and “End” icons. Release the icon.ConfigBEGINVariablesvoid main (void){END}Reading from the chart on the previous page, forward movement requires the left motor to turnclockwise, and the right motor to turn counter-clockwise.4The “Motor Module” configuration windowwill appear. Make sure “Motor Number” is 3and “Clockwise” is selected. Click “OK.”5 Repeat steps 2 and 3, dropping the second motormodule icon right below the first. In the "MotorModule" configuration window, set "Motor Number"to 2 and select "Counter-clockwise". Click "OK".01/31/05Inventor’s Guide8 • 29


programmingautonomous programsprogram two: using the motors, continuedNext, the robot needs to wait three seconds (during which time the motors will remain on).6 In the "Function Blocks" window under the 7"Program Flow" heading, find the "Wait" block.Left-click and drag the "Wait" block into theprogram window. Drop the "Wait" icon on the linebelow the two motor commands so it will occurafter the motors have been turned on.ConfigBEGINVariablesvoid main (void){8 The "Wait" configuration window will appear.The "Wait" function is used to make the9program wait a specified amount of time beforeproceeding to the next icon.The default for the "Wait" is one second (1000milliseconds). You want your robot to waitfor three seconds, so enter 3000 into the"Wait[msec]" box, and click "OK".Your program should now look like this :ConfigBEGIN void main (void)Variables {01/31/058 • 30Inventor’s Guide


programmingautonomous programsprogram two: using the motors, continuedSo far, this program will turn on both motors and wait for 3 seconds. The final step is tostop both motors.10 Repeat steps 2 and 3, dropping the new motormodule block after the Wait block. When the“Motor Module” configuration window appears,set “Motor Number” to 3 and select “Stop”.Click “OK”.11Repeat steps 2 and 3, dropping the new motormodule block just before the End block. When the“Motor Module” configuration window appears,set “Motor Number” to 2 and select “Stop”.Click “OK”.12 Your final code should like like this: 13Compile and Download your code.ConfigBEGINVariables14Refer to the <strong>Programming</strong>Sequence section, page23, for detailed steps oncompiling and downloading.When the program is finished downloading,your robot should move forward for threeseconds, then stop.15Save your program as "intro programtwo". For a refresher on how to save yourprogram, see tips for saving programs onpage 26.Congratulations, you have programmedyour robot to perform a real behavior!01/31/05Inventor’s Guide8 • 31


programmingintroduction to sensorsautonomous programsSensors assist robots in seeing and feeling the physicalworld through which they travel. A sensor will tell arobot one very simple thing about its environment. Theprograms that you write will determine how the robot willreact depending on the feedback from a sensor. Sensorscan be placed in two different categories based on thetype of signals they send or recieve.A brief review of sensors:1Digital sensors can distinguish between exactlytwo different "states". The exact meaning of thetwo states depends on the type of sensor beingused. The robot will interpret information from adigital sensor as either 1 or 0.For example the Bumper Switch can read 1 (whenit is not pressed) or 0 (when it is pressed).2Analog sensors can provide a range of feedback.The feedback provided by an analog sensor rangesfrom zero to a pre-defined maximum limit for thatparticular type of sensor. The robot will interpertfeedback from an analog sensor as a specificnumber between 0 to that maximium value.The Light Sensor and the Line Tracking Sensor,available separately as sensor accessory kits,are prime examples of analog sensors. They canread the relative "lightness" of a tabletop or othersurface as a single numeric value. That valueranges from zero to one thousand.01/31/058 • 32Inventor’s Guide


programmingautonomous programsintroduction to sensors, continuedThe Analog/Digital Port Bank on the Vex MicroController consists of 16 ports that can be reconfiguredto work as Analog Input, Digital Input, or DigitalOutput ports. The ports must be configured to match thetype of sensor that is plugged into them (digital inputfor a digital sensor, etc.).To configure the Analog/Digital ports, double click theConfig icon located on your programming screen.ConfigBEGINVariablesENDvoid main (void){}A window will appear revealing a blueprint of theVex Micro Controller.The section labeled "Analog / Digital" represents thesensor ports on your Vex Micro Controller. Left-clickingthe ports switches the port to either digital input ordigital output. Right-clicking these ports toggles thembetween analog and digital settings.Note that the Analog ports must always be togetheron the bottom, so switching a port to Analog willautomatically change all the ports below it to Analog aswell.Due to electrical load limitations on the Analog/Digitalport bank, you cannot configure a port as an AnalogOutput.Digital ouput ports are used for the Ultrasonic Sensor,and other 5V digital output devices, such as LEDs.Digital OutputDigital input ports are used for Bump Sensors, LimitSwitches, Jumpers, and other 5V digital sensors.Digital InputsAnalog inputs are used for the Light Sensor, the LineTracking Sensor, and any other 5V analog sensor.Analog Inputs01/31/05Refer to the Sensors SubsystemChapter in the "Inventors Guide" or theSensor Accessory Pages which comewith Sensor Accessory Kits for moreinformation.Inventor’s Guide8 • 33


programmingautonomous programsusing a sensoreasyC includes a group of default sensor test files, which will allow you to testyour sensors. First, you will compile and download a sensor test file to yourrobot to test it. Then, you will examine all the parts of this code and how theyinteract.1To open the test file for the bump sensor, click "OpenProject..." in the "File" menu. Open the folder labeled TestCode, then click on the file called "BUMPERTEST". Thenclick "Open".2BUMPERTEST should open and your program window shouldlook like the following:ConfigBEGINVariablesvoid main (void){01/31/058 • 34Inventor’s Guide


programmingautonomous programsusing a sensor, continued3Make sure your robot is set up according to the motor and sensorguide and your robot is on. Compile and download this code to therobot. (Refer to the programming sequence section earlier in thischapter for detailed steps on compiling and downloading.)4At this point, your robot should not be doing anything. Theterminal window should open automatically. If it does not,click on the terminal window icon in the toolbar.5You should see the window below, with text scrolling across it.If you press and release the bump sensor, you should see theBumper Switch output number change between 1 and 0. Pressand release the bump sensor until you are familiar with the itsoperation.01/31/05The terminal window is the window used to display any informationgathered from the robot, not only information from the bump sensor. Ifyou have purchased any of the Sensor Accessory Kits, you will find thateasyC also comes with test programs for all of these, and all the testprograms will function very similarly.Inventor’s Guide8 • 35


programmingautonomous programsunderstanding bump sensor test codeLet's take a closer look at how the bump sensor test code works.AVariablesConfigBEGINVariablesvoid main (void){BCommentsCWhile LoopDPrint to ScreenA1. A variable is like a value-holding "container" witha name (label). Any time you need to store a valuefor later use in a program, you will need to use avariable to store that bit of information. You canthen retrieve the value when it is needed.2. To modify or create variables, open the Variableswindow by double clicking the “Variables” buttoninside the program.ConfigThe screen below should appear:BEGINVariablesb u m p e r1l o o p3. If you enter a number into a variable’s “Value”field, the variable will start with that number init when the program begins. Here, the variable“loop” will have the number 1 in it when theprogram starts, whereas the variable “bumper”will have no value in it initially.4. There are many types of variables, becausethere are different types of data to hold (anumber versus a letter, for instance). Formost basic Vex applications, you will the "int"(integer) type for a variable, because sensor andtimer readings both use this data type.01/31/058 • 36Inventor’s Guide


programmingautonomous programsunderstanding bump sensor test code, continuedBCComments - Comments allow you to leave notes to yourself and othersabout your code. These comments do not affect how the program runs, butare very important in helping others to understand your code (and remindingyourself, if you revisit a program several weeks or months later).While Loops - This is a block of code that willrepeat itself as long as the condition inside theparentheses is true. The condition in the whileloop in this program asks whether (loop == 1),i.e. whether the value of the variable "loop" isequal to 1. The code inside of this loop will runover and over as long as "loop" is equal to "1".As it turns out, the variable "loop" was set to astarting value of 1 in the variable window (seeprevious page). Since we never change the valueof the "loop" variable, we can reason that it willalways be equal to 1, and so this while statementwill repeat its code forever (or at least as long asthe robot is on.)DPrint to Screen - This is the code that allows you to seeinformation in the terminal window. If you double click on theicon next to the PrintToScreen statement, you will see the"Print To Screen"configuration menu.The "Message" field lets you specifytext which you would like to displayin the terminal window.The optional “Variable” field lets you display the currentvalue of a variable in the printed line (it will appear atthe end, after the “Message” text). The “Variable” dropdown menu lets you choose which variable to display. The“directive” menu tells the computer how to display thevariable’s value. %d tells the computer to use a decimalformat, which works well for int-type variables like bumper.The “typecast” menu specifies the type of the variable. Thisshould usually match the type of variable you specified.01/31/05Inventor’s Guide8 • 37


programmingautonomous programsprogram three: using motors and sensors togetherThis program will make your robot move forward forever,unless the bump sensor is pushed in.1Start a new project in easyC by clicking"New Project" in the "File" menu.2Double-click the Variables block in yourprogram to open the "Variables" window.Create a new "int" type variable named"bumper", then click OK.ConfigRefer to the using a sensorsection, page 34, for moreinformation on variables.BEGINVariables3In the "Function Block" window, underthe "Program Flow" heading, find the"While Loop" icon. Left-click on the iconand drag it into the program window anddrop it between the begin and end icons.ConfigBEGINVariablesvoid main (void){WHILEEND}4The "While Loop" configuration menuwill appear. Set the condition of thewhile loop to be "1==1". This has thesame effect as using a variable setto 1, like in the sample bump sensorcode. Click "OK".The while loop will loop for an infiniteamount of time.401/31/058 • 38Inventor’s Guide


programmingautonomous programsprogram three: using motors and sensors together, continued5 Your program should now look like this.ConfigBEGINVariablesvoid main (void){6 In the "Function Block" window, under the"Inputs" Heading, find the "Bumper Switch" iconand drag this into the program window betweenthe { and } brackets of the while loop. Set the"Digital Input #" to 6 (where the front bumper switchis plugged in, see page 33 for setup details), and the"Retrieve to" to the variable you created, "bumper".Click OK when you are done.You have now set the variable "bumper" to be updatedwith the current value of the bump sensor each time theloop is run.7If the bump sensor is not pushed in, then you want themotors to continue moving the robot forward. If thebump sensor is pushed in, then you want the robot tostop.ConfigBEGINVariablesvoid main (void){Since we are storing the bumper sensor's pushed/notpushedstate in the "bumper" variable, that is where theprogram must look to see whether it is being pushed. Ifthe sensor is pushed, "bumper" will have a value of 0. If itis not pushed, "bumper" will be equal to 1.We will use an if-else statement to perform this check.8In the "Function Block" window, under the "ProgramFlow" heading, drag the "If" block into the while loopunderneath the "Bumper Switch" icon. In the "If"configuration window, the first block asks you to definethe condition (just like a while loop). First, click the smallarrow next to "Add Variable" and select "Bumper". Then,click the arrow next to "Add Operator" and select the"==" operation. After the "==" sign, you will enter thenumber 1. The “if” condition will now check whetherthe variable "bumper" is equal to 1. Click OK to continue.01/31/05Inventor’s Guide8 • 39


programmingautonomous programsprogram three: using motors and sensors together, continued8Similarly, drag the Else block below the If block. Your code should look like the program on theleft. Now, recall that if the bump sensor is not being pressed in (that is, bumper is equal to 1),we want the robot to move forward. You already know which combination of icons makes yourrobot move forward (refer to program two if you need a reminder). Drag in two motor modulesbetween the brackets under the "if" statement. Set them up so that your robot will drive forward.Be sure to place the move-forward motor commands in the section immediately after “if(bumper==1)” because you want them to execute when bumper is equal to 1.ConfigBEGINVariablesvoid main (void){ConfigBEGINVariablesvoid main (void){Your program should now look like this.9 The other half of this program's behavior is that if thebumper is being pressed in, we want the motors to stop.Drag in two motor modules between the brackets underthe "else" statement. Configure them so that they form astopping behavior (see progam two).ConfigBEGINVariablesvoid main (void){10Check your code to make sure it looks like the code onthe right. Compile and download your code.Refer to the programming sequence section for detailedsteps on compiling and downloading11Test your code. Your robot should now drive forward untilthe front bump sensor is hit, at which point the robot willstop. If you move the robot so that the front bump sensoris no longer pressed, it will once again move forward.12Save your program as “intro program three”. We will berevisiting this program soon! For a refresher on how tosave your program, see tips for saving programs onpage 26.Congratulations, you have integrated sensor feedbackinto your robot behavior!Your program should now look like this.01/31/058 • 40Inventor’s Guide


programmingprogram four: reversing and turningautonomous programsIn this section, you will enhance the code from program three by making it back up, turn,and then continue on its way when the bumper sensor is hit, rather than just stopping.1Open your saved program three file.Select “Open Project” from the “File”menu, then click on INTRO PROGRAMTHREE and click “Open”.2Before editing the code, save the code as “introprogram four”.ConfigBEGINvoid main (void)Variables{For a refresher on how to saveyour program, see tips for savingprograms on page 26.Your program should now look like this.01/31/05Inventor’s Guide8 • 41


programmingautonomous programsprogram four: reversing and turning, continued3The current programmed behavor is: if the bumpsensor is not being pressed in, the motors turn on;when the bump sensor is pressed in, the motors turnoff.We will edit this program so that instead of stoppingwhen the bump sensor is pushed, your robot will backup, turn right, and then resume moving forward.This means that the new turn-backup code will bereplacing the old stop code icons in theelse statement.ConfigBEGINVariablesvoid main (void){Start by clearing away the old code. Delete both ofthe Motor Module commands in the else statement.Right-click the first icon, then select delete from themenu that appears. A screen will appear asking ifyou are sure; click yes. Repeat for the second motorblock.4Next, we want to start building the new behaviorinto the else statement. Begin with the first action,backing up (the idea is to move your robot clear ofthe obstacle it has encountered).ConfigBEGINVariablesvoid main (void){To do this, drag in two “Motor module” iconsbetween the brackets of the else statement.Configure them so the robot starts moving in reverse.See using the motors on page 27for the motor directionsSee using motors and sensors together,page # for the motor directionsYour program should now look like this.01/31/058 • 42Inventor’s Guide


programmingautonomous programsprogram four: reversing and turning, continued5Set the amount of time for the robot to move with a “Wait” icon likeyou did in program two (page #). Drag a “Wait” icon into the elsestatement under the two “Motor Module” icons. In the “Wait”configuration window, set the “Wait [msec]” to 1000 (one second.)ConfigBEGINVariablesvoid main (void){6To make your robot turn right, drag two “MotorModule” icons below the wait icon, inside theelse statement. Configure them so the robotturns right.ConfigBEGINVariablesvoid main (void){See using the motors on page 27for the motor directions01/31/05Inventor’s Guide8 • 43


programmingautonomous programsprogram four: reversing and turning, continued7To specify the amount of time your robot will turnright, drag a “Wait” icon into the else statementunder the two “Motor Module” icons. In the “Wait”configuration window, set the “Wait [msec]” to 500(which is 500ms, or half a second.) This should makeyour robot turn approximately ninety degrees.ConfigBEGINVariablesvoid main (void){Note: The amount of turning produced by this programwill vary from robot to robot. You may have totweak the timing for your robot to turn away from thewall.8Compile and Download your program.Refer to the programming sequence section fordetailed steps on compiling and downloading.Your code should now look like the program above9Test your code. Your robot should drive forward until the front bump sensor is hit, atwhich point the robot will back up, turn right, and then resume forward motion.10Be sure to save changes to your code. Refer to tips for saving programs on page 26.Congratulations! Your robot now performs an intelligent autonomous behavior!Let your robot run for a while to see how long it can continue roaming around aroom. Identify areas for improvement in the design, and construct and programan improved version.01/31/058 • 44Inventor’s Guide


programmingremote control programsprogram five: using the radio control transmitterThis section will explain how to incorporate RadioControl into your programs. Please make sure your RFreceiver module is plugged into the RX1 port of your<strong>VEX</strong> Micro Controller. The rest of your robot should stillbe configured according to the instructions on page 13.1Start a new project in easyC by clicking"New Project" in the "File" menu.2In the "Function Block" window, underthe "Program Flow" heading, find the"While Loop" icon. Drag this into the programwindow between the Begin and End icons.3Set the condition of the while loopas "1==1" in order to create a continuousloop. Click OK.4In the "Function Block" window, under the"RC Control" heading, find the "Tank -2 motor" icon. Drag the "Tank - 2 motor"icon into the "While" loop (drop it between the{ and } icons as shown). This icon causesthe robot to wait for a signal from the radiocontrol transmitter.ConfigBEGINVariablesvoid main (void){Note that the RC Icons only work when they areinside a loop. The icon must be executed repeatedlyby the program in order to provide continuouscontrol. Otherwise it will only give you radio controlfor an invisibly brief moment, then move on.01/31/05Inventor’s Guide8 • 45


programmingremote control programsprogram five: using the radio control transmitter, continued5The "Tank - 2 Motor" configuration windowwill appear. Leave the RX# set to “0”.067Set the left channel to "3", indicating the verticalaxis of the left joystick on the transmitter will beconsidered the "left" control. Set the right channelto "2", indicating the vertical axis of the rightjoystick on the transmitter will be considered the"right" control.In the "Motor Number" section, set "Left Motor" to"3" and "Right Motor" to "2". This specifies whichmotors are control, by the corresponding joysticksselected in step 6. The motor numbers aredetermined by your current motor set up, which isdescribed in the motor and sensor setup section onpage 38.8Click OK to continue. The icon should appearbetween the “Begin” and “End” icons with“Tank2(0,3,2,3,2);” beside it.ConfigBEGINVariablesvoid main (void){Note: “Tank2” means that you chose the Tankstylecontrols with a two motor setup. Thefirst number, “0”, shows that the programwill automatically use the RX port that has asignal. The first 3 and 2 following that show thetransmitter channels. The second pair of numbers,3 and 2, show which port you set the left and rightmotors to, respectively.1011Compile and download your code. (Refer to the “<strong>Programming</strong>Sequence” section for detailed steps on compiling and downloading.)Test your code. Your robot should be controllable using the radiocontrol transmitter. The right joystick will control the right motorand the left joystick will control the left motor.12 Save your program as “intro program five”. For a refresher on howto save your program, see tips for saving programs on page 26.Congratulations, you have programmed your robot sucessfully!!01/31/058 • 46Inventor’s Guide


programmingautonomous and remote control programsprogram six: combining autonomous and radio controlIn this section, we will explain how remote control codecan be combined with autonomous code. In this examplewe will adjust the code from program four to includeremote control similar to that in program five.1Open your saved program four. Select “OpenProject” from the “File” menu, then click onINTRO PROGRAM FOUR.ECP (or whatever yousaved it as) and click “Open”.Refer to the tips for saving programs section,page 26, if you are unsure of how to do this.Recall that in this program, the motors switchedon autonomously if the bump sensor was not beingpressed in. When the sensor was hit, the robot wouldback up, turn, then continue on its way.ConfigBEGINVariablesvoid main (void){Now, you will modify this code so that instead ofdriving forward, you will have control of the motorsvia the radio control transmitter unless the frontbump sensor is pressed. This means that code toenable radio control will replace the oldmove-forward icons in the if-else statement.Your program should now look like this.01/31/05Inventor’s Guide8 • 47


programmingautonomous and remote control programsprogram six: combining autonomous and radio control, continued2Start by clearing away the old code. Deleteboth of the “Motor Module” commands in theif statement. Right-click the first icon, thenselect delete from the menu that appears. Ascreen will appear asking if you are sure; clickyes. Repeat for the second motor block.ConfigBEGINVariablesvoid main (void){Your program should now look like this.3Next, you want to put tank control identical to thecode you used in program five into the if statement.To do this, drag the “Tank-2 motor” icon from the“Function Blocks” window into the program areaand drop it between the { and } of the if-statement.Set up the “Tank 2-motor” configuration windowas shown.For more information about putting tankcontrol into a program, refer to program fiveand the using radio control section.001/31/058 • 48Inventor’s Guide


programmingautonomous and remote control programsprogram six: combining autonomous and radio control, continuedConfigBEGINVariablesvoid main (void){Your program should now look like this.456Compile and Download your code. Refer to the programmingsequence section for detailed steps on compiling and downloading.Test your code. Your robot should now be controlled by theradio control transmitter, as long as the front bump switch is notpressed in.Save your program as “intro program six”.For a refresher on how to save your program, see tips for savingprograms on page 26.Congratulations! You have successfully combined autonomousand radio control code to give you a robot that can be manuallycontrolled, but has a built-in safety mechanism that backs therobot up and turns it away from an obstacle when it detects acollision.01/31/05Inventor’s Guide8 • 49


programmingadditional helpabout easyCIn addition to the tutorials and instructions provided herein the programming guide, easyC has its own set of helpfiles that may help you find the answers you seek.1Help on any specific function block (like a “Wait” block or a“Timer” block) can be found by dragging the icon you are curiousabout into the program window. The configuration window shouldappear and there will be a “Help” button in the lower right handcorner of the window.2For more general information about using easyC, try the help menuon the menu bar at the top of the screen.01/31/058 • 50Inventor’s Guide


programmingtroubleshootingtroubleshootingThere are different problems that you may encounterwhile programming with easyC. Here are some of themore commonly encountered ones, and some possiblesolutions.<strong>Programming</strong> Strategies:Describes strategies to help you program more efficiently.Compilation Errors:Covers errors in your code.Other Errors:Covers download and access right errors.Download Errors:Describes errors when downloading your code to the robot.Access Right Error:Covers errors that occur when you are not an administrator.NOTE : If you would like to downloadthe default code that accompanies yourrobot, refer to page 22.01/31/05Inventor’s Guide8 • 51


programmingprogramming strategiestroubleshootingThis section will outline useful coding habits that mayhelp you program more effectively.123456789Test each section of your program to make sure each one works individually. The program as a wholecan’t work if the parts don’t.Build your program step by step and test at intervals. Never write out the whole program at once.Use “Wait” and “Print to Screen” commands at strategic points in your program. This will help youidentify where your errors occur.Use comments to document what important lines in your code are doing. You aren’t going toremember every single line of code when you come back to your program in a week, and it helps otherprogrammers on your team to understand how your code works.When using loops or if (-else) statements, use the drop-down menus to help write the condition.Don’t use the “User Code” icon unless you have experience in programming. Using the “User Code”icon allows you to write your own code that the easyC software cannot help you correct.easyC can not identify all of the errors you will make, because your incorrect code may still look likea legitimate program. Programs may compile correctly, yet will not work as you want them to.If you are using sensors, be sure you connect them to an input port of the correct type. For more onhow to change this refer to the intro to sensors section (page 8•32).Save your code often. Also save your code under a different name before making major changes soyou can revert back to an earilier version if needed.Before beginning to code a program, identify the behaviors you will need, and how they will need bearranged. You can do this by simply writing out the steps or using a flow chart like the one below.01/31/058 • 52Inventor’s Guide


programmingtroubleshootingcompilation errorsCompilation errors are errors in your code that preventthe <strong>VEX</strong> Micro Controller from understanding theprogram. This section will teach you how to use easyC tofind errors in your code.If you click on the “Build and Download” button and you havecompilation errors in your code, you will receive thiserror message.ConfigBEGINVariablesvoid main (void){1. The output window willdisplay what type of errorhas occurred and the linenumber indicating where theerror is located.2. If you click on the errorin the “Output Box”, the linethat the error is on will behighlighted in the“C <strong>Programming</strong> Window”.The function block will alsobe selected01/31/05Inventor’s Guide8 • 53


programmingtroubleshootingcompilation errors, continuedCompilation errors will be displayed in the “Output Window”according to the following format:Error [error number] line# (the line number of the error) : description of errorThere are several common errors displayed in the “output window”:1 “Symbol has not been defined”: This occurs when you misspell avariable name or if you try to use a variable that has not beendefined in the Variable Window at the top of the program.2 “Syntax error” : This occurs most frequently when you do notcomplete the condition in an if statement or loop. For example,in “if( loop == )”, the “loop == “ condition is not a completestatement.3 The output window may also point out some warnings of possibleerrors in your program, even if it compiles correctly. One exampleof this is “expression is always true”, which occurs when you usean expression that is always “true” in an “if-else” conditionalstatement (the program warns you that this is suspicious – after all,why would you want an if-else statement that never used the elseblock?)01/31/058 • 54Inventor’s Guide


programmingother errorstroubleshooting1. Download errorsDownload errors occur when you are attempting to download codeto your robot. These errors can occur because your hardware is notset up properly or because your software is not configured properlywith your hardware. This section will teach you what the differentdownload errors mean and how to correct them.If you are downloading code and you recieve this errormessage, try the following steps to correct the error.1 Check to make sure your hardware is set upaccording to the programming hardware page(page 8•13).2 Make sure your robot is on.3 Make sure you have properly installed the USB-toserial driver and your COM port is set properly(refer to installing the easyC programming software,page 8•11).If the loader freezes up and then closes in the middle ofdownloading, try the following steps to correct the error:1 Check to make sure your robot was not turned offduring download. Check your battery levels.2 Be sure all cables are plugged in.2. Access rights errorsAccess rights errors will occur if you are not set up as anadministator on your computer.This error message will appear if you are not anadministrator and you attempt to compile a program.This error message will appear if you are not anadministrator and you attempt to save a file in arestricted location.01/31/05To solve this problem, talk to your system administratorabout getting your user privileges upgraded to includefile write access to the folder on the computer whereeasyC is installed. This is “C:\Program Files\Intelitek”on most machines.Inventor’s Guide8 • 55


programmingkeeping countBuild and program a wandering robot that will runstraight until it hits a wall, then back up and turn, allthe while keeping track of the number of walls it has hit.After hitting a wall for the third time, the robot mustcome to a complete stop.challengesThe code solution to thechallenge can be downloadedfrom www.vexrobotics.com1The robot must begin facing a wall.12Once it hits a wall, it must reverse for1 second, then turn or pivot right, andthen resume traveling forward.3The program should stop after the thirdwall collision (it can back up and turn,but should not move forward).2Use this space to draw a flowchart and write your solution:01/31/058 • 56Inventor’s Guide


programmingheadache!Use a bumper switch to help you navigate a maze by“feeling” your way through. You will be able to see themaze ahead of time to plan your route, but your robot mustuse the bumper switch sensor to detect walls.challengesThe code solution to thechallenge can be downloadedfrom www.vexrobotics.com1 You will be able to see the mazeahead of time to plan a route.End2 Your robot must be able to movefrom the starting area to the finisharea without human assistanceonce turned on.34The robot must use wall collisionsto guide it through the maze. Itcannot navigate by timed movementsalone.Hint: Like most long sequencesof behaviors, this one is easier toprogram if you write and test yourprogram one segment at a time.2314BeginUse this space to draw a flowchart and write down ideas:01/31/05Inventor’s Guide8 • 57


programmingafterwordCongratulations! Your experience with the Vexprogramming kit will enable you to not only bettersolve existing problems using the Vex robot, but in factaddress an entirely new set of tasks that you couldn’t evenattempt without programming.Additionally, you can now explore all of the otheraccessories available for the <strong>VEX</strong> kit. This includesparts such as additional sensors: the Light Sensor, LineFollower, Optical Shaft Encoder, and Utrasonic Sensor.With these new tools at your disposal now that you knowhow to use the programming kit, your robot’s capabilitieswill grow by leaps and bounds.As always, if you wish to find more information aboutcompetitions and challenges, or about Vex in general,please visitwww.vexrobotics.com01/31/058 • 58Inventor’s Guide

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!