Introduction ​ VEX Robotics has a steep learning curve and can be hard for both new and experienced teams. We hope to provide a wealth of information here, giving every team the resources they need to build high-quality, competitive robots. 🛠 Building 💻 Coding 📗 Engineering Notebook 🏆 Tournaments If you have suggestions or would like to contribute, let us know! Building Comprehensive Building Guide CAD Design "Measure twice, cut once" CAD (Computer assisted design) is an essential part of VEX robotics. It allows teams to fully plan out the robot on the computer before constructing anything in the real world. Advantages of CAD Disadvantages of CAD Plans out the robot fully ahead of time None Reduces the time it takes to build ​ Adds an element of professionalism to the engineering notebook ​ OnShape is the recommended software for CAD in VEX due to its ease of use and VEX part libraries, but other softwares work just as well. Onshape | Product Development Platform Here's a good set of video tutorial for CAD in OnShape: ​https://www.youtube.com/watch?v=8rkEL2l4pvM&list=PL58YBuL9CL7KdaFquOuCasoTzGwnjHFUN&index=1​ How to use CAD As important as it is, CAD is not the end-all. It is a tool that you use to plan out where everything goes on the robot. However, no robot has ever perfectly matched it's CAD design, because there are more factors to consider in the real world. For example, it's not necessary to model screws in the CAD, since it is already clear where they need to be. On the other hand, important aspects of the robot--the drivetrain and additional mechanisms--should be present in the CAD, so that you know how to build them in the real world. Example CAD design (Over Under). Note the extensive labelling and level of detail. We don't recommend this intake design. Design Tips CAD Design can be intimidating at first; here's a few tips: * Don't be afraid to take inspiration from other robots. Watch matches online. Study reveal videos. Ask other teams questions at tournaments. If you see a design you like, imitate it--don't copy. * Imitate means "take inspiration from without copying screw-for-screw, and make it better along the way". It's okay to imitate other designs that work well. It's not okay to copy the entire robot, down to the last hole of the C-channels (i.e. holecounting). * Don't overthink the positioning of the brain, battery, and air tanks. These don't have to go in the CAD design, because their positioning can usually be figured out later. * Ask for help. Get experienced robotics members to review your CAD before you build it--this prevents you from having to take apart half of the robot to fix one minor flaw later on. * Simpler is better. A well-optimized simple design will beat a complex one nine times out of ten. Less mechanisms means less things can go wrong on the robot, so don't overdesign! Here's some specific tips for VEX Robotics: * Use 2-3 cross-braces on the drivetrain that go across the entire length of the robot, preferably as far apart as possible. This prevents the chassis from bending over time (not good). * Use standoffs everywhere! Seriously, standoffs are amazing for bracing, and come in handy when you're trying to mount a mechanism to the robot or brace something. * Study how other successful robots mount mechanisms to the robot. There are myriads of reveal videos and robot explanations on YouTube; even looking at robots from previous years can give you ideas on how to design the structure of your robot. Imitate, don't copy. Best Practices Ideally durable, lightweight, and robust In Vex, there are many techniques to getting a high-quality build. The goal is to allow the robot to last multiple competitions without breaking while keeping it as light as possible. Triangle Bracing Triangle bracing uses standoffs at odd angles to brace higher points on the robot. This greatly improves the stability of the higher mechanisms on the robot. In the picture below, the tower in the middle of the robot will not bend over time due to the triangle bracing. For this type of bracing, we recommend using shaft collars screwed into each other and into standoffs like so: Note how the shaft collars are oriented Lighter is Better Lighter robots move faster and can usually outscore heavy robots. To save weight, always use the thin nylock nuts. They are about 50% lighter, which adds up when hundreds of them are used across the robot. Additionally, always use aluminum metal to build the robot. Vex also offers steel, which is 50% stronger. However, it is also 136% heavier--not worth it. Here's the same C-channel in both aluminum (left) and steel (right) varieties. Note the massive weight difference between the two pieces! Center of Gravity Ideally, the center of gravity should be two things: * Low: prevents the robot from tipping over * Centered: makes autonomous routines more accurate Practically, this means that the bulk of the weight on your robot should be as low as possible. Additionally, try to have some balance in the weight distribution side-to-side. For example, mount the brain/battery and the air tanks on opposite sides of the robot to balance it out. Note how all 6 drive motors and the air tank are as low as possible Zip ties! Zip ties are the duct tape of Vex Robotics. They work well in a pinch for meager structural support, but they don't hold up in high-stress situations. One good application of zip ties is on bearing flats for the drivetrain. That's because the bearing flats are not under any lateral stress. Additionally, this saves weight compared to the alternative (screws and nuts). This should not be viable, but it is Using zip ties instead of screws and nuts to attach bearing flats saves about 0.01 pounds per bearing flat. If you use 20 bearing flats on the robot in total, you can save 0.2 pounds of weight on the robot. Every little bit of weight reduction matters. Bearing flat attachment method Weight Zip ties 0.001 lbs Screws and nuts 0.011 lbs However, zip ties should not be used for high-stress or pivotal connections, as they are prone to break over time. Drive Trains Unleash your inner NASCAR Drive trains are not technically required, but nearly every robot has one. They allow the robot to traverse the field, and serve as a foundation for the rest of the the robot. Here's the simplest possible drivetrain you can have: Simple tank drivetrain CAD This tank drivetrain features at least 2 omniwheels on each side of the robot. Usually, 4 or 6 motors will power these omniwheels either directly or through gears. This drivetrain can turn in place and go forwards and backwards, but it cannot strafe side-to-side (which is usually not necessary). Here's another example of a more complex tank drive with 6 motors, 6 wheels, and a gear system: Example drivetrain CAD Another type of drivetrain is the X-drive. This drive has more maneuverability, but reduced torque and pushing power relative to the standard tank drive. Photo credit: Team 1619Z While the increased maneuverability does offer an advantage in niche scenarios, X-drives are very weak against defense by others teams. For example, out of the 20 teams that won their division during Spin Up Worlds (i.e. top 20 teams in the world), all 20 of them used a tank drive. There are another couple types of drivetrains, but these are not competitively viable in VEX Robotics. ​ ​ ​ Overall, the recommended drivetrain for both new and experienced teams is the standard tank drive. Design Guidelines Let's assume you're going with the tank drivetrain (please do!). Here's a few general guidelines to keep in mind while designing it. * Smaller is generally better, but don't make a drive so small that it can't fit other mechanisms on the top of the robot * Don't use any more gears than is absolutely necessary, to reduce friction * Have the wheels as far apart as possible, which makes it harder for the robot to tip over * Use 2-3 cross-braces, and have them as far apart as possible. This keeps the chassis from bending under heavy defense Here's another example CAD that follows these guidelines. Always CAD the drivetrain before building it! Over Under drivetrain CAD from 96504C Additional Resources Here's two videos on how to square the chassis--this is very important for having consistent autonomous and a low friction drivetrain. ​ Screw Joints Screw joints are an advanced build technique that reduces friction and increases structural stability on the drivetrain, compared to using axles on the wheels. Here's one type of screw joint: Layout for one type of screw joint Here's how to attach the gear to the wheel for this type of screw joint: And here's another type of screw joint using a 2.75" wheel with a 48T gear: Boxing No, not that type of boxing Boxing is an advanced build technique that improves the stability of a connection. The basic idea is to prevent a C-channel from bending by supporting it at two points rather than one. This is done with a long screw and 7/8" of spacing on the inside of a C-channel. Here's an intake before and after boxing. In the picture to the left, the C-channel bent under heavy defense. It was fixed in the picture to the right by boxing, and the C-channel never bent again. ​ ​ ​ We also recommend boxing the cross-braces on the drivetrain as shown below. This prevents the drive C-channels from bending and makes the robot more durable. Note that only the corner screw needs boxing Bearing flats It turns out that the square holes in vex metal pieces aren't a great fit for a rotating axle. Yes, they technically work, but the axle is highly unstable, and the friction is egregious. Note the shape of the hole in the metal The solution? Bearing flats! Bearing flats are essential for having low-friction drivetrains, and also for other mechanisms on the robot. They keep shafts aligned to the center of the hole, preventing it from touching the metal (which adds friction) or wobbling. Bearing flats should be used on either side of an axle to support it and reduce friction. However, a motor also supports the axle, so there is no need for a bearing flat right next to a motor: On the drivetrain, bearing flats should be used for both axle and screw joints (as possible), since they do reduce friction. For example, in the drivetrain below, the motor shafts have one bearing flat on the outside to keep the motor axle stable. Note the zip ties. Yes, this works, and it works well! ​ Fixing Friction Not this again... Friction on the drivetrain can be caused by any number of issues. Testing Friction Luckily, it's relatively easy to test drivetrain friction. Attach all of the gears and wheels, but not the motors and motor cartridges, like so: Then, give the drivetrain a good spin with your hand, as fast as you can. The drivetrain should keep spinning for at least: * 3 seconds, if you have axle joints * 5 seconds, if you have screw joints This is called the freespin time, and it's a great way to test the friction on the drivetrain. The longer the freespin time, the less friction there is. Fixing Friction If the freespin time on the robot is longer than acceptable, there is friction somewhere. Here's a few potential sources of friction: Bent axles If the drive axles are bent, then nothing else can really work. To test if an axle is bent, press it against something you know is flat and look for a gap between the axle and the flat surface. Do this for all four sides of the axle. Note the gap between the wooden table and the axle If it is bent, then simply replace the axle and throw away the old one. There's no reason to keep bent axles around. Tight spacing On either axles or screws, too much spacing can cause friction issues. That's because the spacers rub against the drive C-channel, which adds resistance and extra friction. The wheel should be axle to wobble back and forth on the axle/screw by about 0.25 mm. If it can't wobble a little, then likely the spacing is too tight. Remove some of the spacers and replace them with shorter ones. In the images above, there isn't a small gap anywhere along the axle. Thus, the spacing is too tight; this will cause friction issues. In this case, removing a washer would be the best way to fix it. Misaligned drive C-channels If the drive C-channels are even slightly misaligned, then that can cause friction because the axles won't be perfectly perpendicular to the inside face of the drive C-channels. Make sure to square your chassis before you start building the drivetrain to resolve this problem. Extraneous shaft collars Shaft collars are essential in VEX Robotics. However, there should never be shaft collars on the outside of the drive C-channels--they only cause extra friction. One shaft collar on the inside of an axle is enough to lock it in place. Bad bearing flats Sometimes, bearing flats go bad or can become misaligned with the holes in C-channels. If a bearing flat seems to be causing a problem, try replacing it. Bad motor cartridges / motors Make sure to test each motor before putting it on the drivetrain. Ideally, each motor (with the motor cartridge in) should not draw more than 0.1 - 0.2 watts of power at max speed. Use the "devices" screen on the brain to test the motor, and if it draws more than 0.2 watts of power, try to find a different motor with less internal friction. Additionally, make sure to test each cartridge as well. Bad motors and cartridges ruin a good drivetrain. ​ 450 RPM on 2.75" The best drivetrain In this tutorial, we'll show you how to build a 6-motor 450 RPM on 2.75" drivetrain, one of the best in the world. This drivetrain is fast, low-centered, and easy to build on. We'll start with the wheel assembly. We used 1.5” screws, ¼” spacers, and nylock nuts to connect the 48T gears to the 2.75” wheels as shown. There are two screws that go through opposite sides to balance the weight. Next, we attached the bearing flat on the inner drive C-channel using one zip tie. That’s because the screw joint will also help to secure the bearing flat in. After that, we found the best spacing for the screw joint. We used washers on both inside edges to reduce friction, and keps nuts to hold the screw joint in place. Here’s how it looks when it’s all put together: Before we could add the bearing flats, we had to shave down the corner of a few so they wouldn’t hit the motor caps. We used a sandpaper attachment on a Dremel and cut the corners like so: Then, we attached all of the bearing flats on the inside of the drive using zip ties. The shaved upper corners of the bearing flats are circled in green. Next, we attached the three motor caps using 0.25” locking screws: Then, we added the rest of the wheels using the same screw joint: Next, we mounted the bearing flats for the motor axles, using zip ties to save weight. After that, we found the best spacing for the motor axles. Again, we used washers to reduce friction. The shaft is 3” long, and fits perfectly into the motor without sticking out past the bearing flat. And with that, the left side of the drivetrain is complete! We made the right side in the exact same way, except mirrored. To attach the back cross-brace, we boxed the back hole of the C-channel and attached it to a 1” standoff going up. The boxing adds extra stability and prevents the C-channel from bending. We attached the rest of the cross-brace in the same manner, like so: Finally, we added the front cross-brace using 0.25” locking screws and eight ½” standoffs. Two cross-braces greatly increases the stability of the drivetrain, and prevents it from bending over time. With that, the drivetrain is complete! Motors Vroom Vroom Motors are an essential part of VEX Robotics, as they convert the chemical energy stored in the battery into usable mechanical energy. There are two types of motors: 11-watt (11W) and 5.5-watt (5.5W) motors. 11W motors Specifications: * Power: 11 Watts * Torque: 2.1 N⋅m * Weight: 0.342 lbs or 155 grams ​ ​ 5.5W motors Specifications: * Power: 5.5 Watts * Torque: 1.3 N⋅m * Weight: 0.20 lbs or 91 grams ​ ​ Each robot is allowed 88W of motor power total. Here's a table showing some possible combinations of motors that can be used on the robot: # 11W motors # 5.5W motors 8 0 7 2 6 4 ... ... Motor Cartridges There are three types of motor cartridges for the 11W motors. Each one spins at a different RPM as shown below: Hot Swapping Hot swapping allows teams to change out broken or overheated motors for good ones without having to unscrew the motor cap (an arduous process). Hot swappable motors have rubber bands that keep the motor body secured to the motor. To make a motor hot swappable, remove the four screws that keep the motor cap secured to the motor body. Then, wrap two rubber bands around the motor as shown in the picture below. Make sure the motor is securely in place, and replace the rubber bands regularly. Example hot swap Metal Structural stuffs The basic structure of every VEX robot uses metal. Specifically, aluminum C-channels are used to construct the chassis and other mechanisms on the robot. These C-channels are relatively lightweight, yet still are very resistant to deformation under stress. Standard 1x2x1x25 C-channel Here's a few other types of metal structure available: 5-wide C-channel 2x2 L-channel 3-wide C-channel ​ However, sometimes a C-channel is overkill for applications on a robot. By cutting a C-channel in half (the long way), you can form 1-by L-channels like the following: These L-channels are good for areas of the robot that aren't under a lot of stress. That's because they're very light, but also less robust than a C-channel. However, teams have innovated ways to use other metal pieces for support. For example, high strength shafts are exceptionally durable and highly resistant to bending. They can be attached using the shaft collars or by drilling holes through the shaft. The shaft acts as a cross-brace and helps hold game objects. Pneumatics These pack a punch In Vex Robotics, teams can use two things to do active mechanical work: motors and pneumatics. Pneumatics use the power of compressed air to activate mechanisms on the robot. However, each actuation uses up a little bit of air each time, so the force from pneumatics slowly decreases throughout a match. Despite this, they are very useful in a variety of mechanisms. For example, here's a pneumatic that is used to activate wings on an VEX Over Under robot: To set up a basic pneumatic system, you need three components: * Air tank: Stores compressed air * Solenoid: Directs compressed air * Piston: Uses compressed air Here's a simple pneumatic system. In summary, compressed air is stored in the air tank to the left, and then directed by the solenoid to either expand or contract the piston. The air tank is filled up with a bicycle pump or air compressor through the Schrader valve. From there, pneumatic tubing connects it to the double-acting solenoid. The solenoid directs the air to one of two output valves that lead to the two sides of the piston. Also, there's a plug in the right side of the solenoid to prevent the air from coming out of the system. Simple pneumatic system setup (the new pneumatics) For information on how to code the pneumatic system, check out this page: 🌬 Coding Pneumatics Best Practices Here's a few tips to keep in mind while building with pneumatics: * Keep the air hose between the solenoid and pneumatic piston as short as possible, to minimize the amount of air lost in each actuation. * Pneumatic pistons are designed to withstand an incredible amount of force parallel to the direction they extend in, but they are not designed to resist bending. * Tighten each valve fitting all the way to prevent leaks. If there is a leak, and you can't find where, apply a small amount of soapy water to each valve fitting connection. If the soapy water starts to bubble at a valve fitting, then air is leaking there. * ​ * * So, that's where the leak is! Additional Mechanisms 3D Printing Non-functional, but cool Unfortunately, 3D-printed parts with a function are not permitted on the robot. However, you are allowed to have decorations or license plate holders that are 3D-printed. In fact, we strongly recommend these license plate holders, because they make it very easy to change colors between matches, saving time. 3D printed license plate holder Here's the file; no supports are needed when 3D printing it. Robotics-license-plate-holder3.stl107KB Binary ​ Ratchets Ratchets allow certain mechanisms on the robot to only activate when a motor spins in one direction. By combining multiple ratchets, a team can add more functionality to their robot. The basic premise of a ratchet is that a gear or sprocket is attached to a shaft such that it can spin freely around it. When the shaft rotates, the gear or sprocket does not necessarily rotate with it. There is also a smaller gear, right next to the primary gear/sprocket that does rotate with the shaft. A small screw on the primary gear/sprocket is then rubber banded so that it "catches" on the smaller sprocket when it turns in one direction, but not in the other. Outer sprocket rotates; the shaft does too Outer sprocket rotates; the shaft stays still To build a simple ratchet, first obtain and assemble the following. Note that a 6-tooth 8P sprocket will usually work for the smaller gear. Additional testing might be required to find the best spacing on the screw in the picture to the right. Also, the larger sprocket can be swapped out for a gear. Make sure to use the circular inserts! Now, put both of the above sprockets on the same shaft. The next step is to zip tie a small rubber band to the large sprocket, as shown below, and wrap it around the screw. This keeps the screw locked into the smaller sprocket when the axle is turning. Catapults Launching stuff Catapults are a common launching mechanism. They are simple, easy to build, and quite effective at launching all sorts of game objects. Before we can get started with catapults, we first have to go over slip gears. These are gears with either one or two sections of teeth shaved off, like so: The simplest catapult possible is a slip gear directly linked to a catapult arm. The slip gear pulls back the catapult to a certain point with the teeth that are on it. Then, when the section of the slip gear with the teeth shaved off reaches the gear on the catapult, the two gears disengage. At that point, the rubber bands on the catapult launch it forwards, along with any game object on the catapult. Here's a demonstration, courtesy of team 491A and the Purdue Sigbots Wiki: Intakes Intakes are mechanisms designed to pick up different game objects and put them into a robot. There are a wide variety of intakes, and we'll show you a few of them here. The first common type of intake uses an array of flex wheels on a rotating arm. Flex wheels have a lot of grip, which makes them good at grabbing game objects. Additionally, the flex wheels can lift up and down, allowing game objects to come into the robot. Note the cross-bracing and C-channel across the intake that stabilizes it. Simple Spin Up intake Here's another example of a flex wheel intake, but this one is vertical instead of horizontal: Image: 62A, BLRS wiki Another common type of intake uses rubber bands wrapped around sprockets as shown below. Rubber bands conform to the shape of the object in the intake more than flex wheels do, which can be helpful depending on the game object and intake spacing. While flex wheels and rubber band sprockets are the majority of intakes, teams can also wrap a single layer of anti-slip mat around a rubber band intake for better durability. Lifts No, not that kind of lift. Lifts are any mechanism that raises one part of the robot up, usually to score points or to achieve some other purpose. One of the most common types of lifts is the four-bar. This simple lift raises up a small bar, while keeping it parallel to it's initial position. Another variant of the four-bar is the double reverse four-bar (DR4B). This type of lift uses two four-bars in tandem that lift the desired mechanism up even higher. To build a four-bar, connect two C-channels in parallel as shown in the videos. Coding We'll use VEXcode Pro V5 Getting Started We'll show you how to get started coding the robot using VEXCode Pro and C++ First, download VEXCode Pro and install it. Then, open the program and create a new project. Start Coding Let's write a simple C++ program to set up the robot: #include "vex.h" ​ using namespace vex; ​ int main() { vexcodeInit(); //leave this line here! Everything else has to come after it. //prevent the main loop from exiting while(true) { wait(20, msec); } } In this code: * We include the necessary VEX header file, "vex.h", to access VEX V5 API functions and classes. * We add using namespace vex; to reference vex motors and classes natively. * We create the main function, which is run when the program is started. * We call the vexcodeInit function--always do this. * We use the wait function in a while loop to prevent the code from exiting before the robot can do anything Building and Downloading Your Code 1. 1. 2. Connect your V5 Brain to your robot and turn it on. 3. 2. 4. Connect your computer to the V5 Brain using a USB cable. 5. 3. 6. Click on the "Download" button (at the top right) to transfer your code to the V5 Brain. Note that the code above doesn't make the robot do anything quite yet; it is just a foundation to build on. Your first order of business should be coding the drivetrain. See this article: 🚗 Drive Code Expanding Your Knowledge Now that you've successfully programmed your VEX V5 robot to perform a simple task, you can expand your knowledge by exploring the VEX V5 C++ API and trying out different sensors and motor configurations. The VEX V5 C++ API documentation provides detailed information about classes and functions you can use to control your robot. VEX V5 C++ API: vex Namespace Reference Note: C++ is not an easy language to learn and it is often used by the most highly skilled programmers. Expect to fail many times, it is normal. Drive Code *Technically optional, but highly recommended You probably want the robot to move around. However, the robot doesn't just do this on its own; you have to program it. In this tutorial, we'll show you how to do that with the double arcade control scheme--the left joystick moves the robot forward and backward, and the right joystick turns the robot. We'll start off by adding the drive motors to the list of devices. In this example, we'll use a 6-motor drivetrain with the left and right motors plugged in to the following ports. Your port numbers can be different; all that matters is that the motors are named well and match up with the ports on the physical robot. For a four-motor drive, just leave out Right3 and Left3 Now, we can start coding. For the sake of clarity, we'll put all of our drive code in a C++ function. Here's the format for a function in C++: void driveCode() { //drives the robot around based on controller input, double arcade controls } The first order of business is to get controller inputs. Make sure you have a controller listed in your devices menu: Now, we can get the inputs from the joysticks and store them in integer variables. The left joystick will control forwards and backwards motion in a straight line, so we'll store that value in a variable called straight. Next, we'll store the value for the right joystick in a variable called turn, since the right joystick turns the robot. Put the following code in the driveCode() function: //Get controller inputs int straight = Controller1.Axis3.value(); //gives a number -100 to 100 int turn = Controller1.Axis1.value(); Now, we need to calculate the motor power, in percentage points, that we should apply to each side of the drivetrain. We'll use two variables, left and right, to keep track of the percentage motor power we will apply to the left and right sides of the drivetrain. The following code calculates motor power, and it should be in the driveCode() function, right after the previous code. //calculate proper motor powers int left = straight + turn * 0.7; //the 0.7 makes the turns less intense int right = straight - turn * 0.7; Why the 0.7? Now that we have calculated the motor powers for the left and right sides of the drivetrain, we just have to apply that power to them. Since we have 6 motors in this example, we'll apply the motor powers to all six motors. //Spin the drive motors at the calculated velocity Left1.spin(forward, left, percent); Left2.spin(forward, left, percent); Left3.spin(forward, left, percent); Right1.spin(forward, right, percent); Right2.spin(forward, right, percent); Right3.spin(forward, right, percent); Let's put all of it together so far! Make sure to put this function before the main loop. void driveCode() { //drives the robot around based on controller input, double arcade controls //First, get controller inputs int straight = Controller1.Axis3.value(); //gives a number -100 to 100 int turn = Controller1.Axis1.value(); //Calculate proper motor powers int left = straight + turn * 0.7; //the 0.7 makes the turns less intense int right = straight - turn * 0.7; ​ //Spin the drive motors at the calculated velocity Left1.spin(forward, left, percent); Left2.spin(forward, left, percent); Left3.spin(forward, left, percent); Right1.spin(forward, right, percent); Right2.spin(forward, right, percent); Right3.spin(forward, right, percent); } Looks great! but if you add this code to your program, nothing will happen. We've made the function driveCode(), but we haven't called it yet. Now, we need to add in another function called userControl that runs when the driver controlled period in a match is active. //driver control code, is activated when the driver control period occurs void userControl() { while (true) { //run this code indefinitely driveCode(); //update the drive motors to be at the right power wait(20, msec); //don't hog the CPU } } When the controller is told to run driver control during a match, your code needs to recognize that and call the right function. Thus, we'll initialize a Competition variable at the beginning of the main file, after the using namespace vex; line. competition Competition; Now, update your main function to call the userControl function when the driver control period starts: int main() { //Initializing Robot Configuration. DO NOT REMOVE! vexcodeInit(); Competition.drivercontrol(userControl); //You might have more code below, leave it } With that, you should have a fully functioning drivetrain! If the driving seems off, reverse directions of the the motors (try many combinations) until it works properly. Coding Motors In this tutorial, we'll show you how to code additional mechanisms on the robot, like an intake or catapult. Specifically, you'll learn how to spin a motor forwards and backwards at the press of a button. First, add the motor to the devices list. In this example, our motor is named Motor Next create a function that spins the motor forwards at full voltage: //Spin the motor forward at full voltage void spinMotorForward() { Motor.spin(forward, 11, volt); } Now, let's create another function to spin the motor backwards at full voltage: //Spin the motor backward at full voltage void spinMotorBackward() { Motor.spin(reverse, 11, volt); } Thirdly, we need a function to stop the motor from spinning when the button on the controller is released: //Stop the motor void stopMotor() { Motor.stop(); } All of this code is great, but none of it will run unless we set up the proper callbacks. We'll use the buttons L1 and L2 in this example, but feel free to change it to any buttons you would like. Put the callback code in the main function, so that the controller buttons activate the functions that spin or stop the motor. int main() { //Initializing Robot Configuration. DO NOT REMOVE! vexcodeInit(); //Set up the motor callbacks Controller1.ButtonL1.pressed(spinMotorForward); //when button L1 is pressed, spin the motor forward Controller1.ButtonL2.pressed(spinMotorBackward); //when button L2 is pressed, spin the motor backward ​ Controller1.ButtonL1.released(stopMotor); //when button L1 is released, stop the motor Controller1.ButtonL2.released(stopMotor); //when button L2 is released, stop the motor ​ //there may be more code below, leave it be } Now, download the code and test to see if it works! Coding Pneumatics Pneumatics can be intimidating at first, but the code for them is simple. In this tutorial, we'll show you how to make a toggle button for a pneumatic piston on the robot. Start by setting up the pneumatic in VEXCode Pro. It's a 3-wire DigitalOut device: ​ ---> ​ Now, we need to make a variable storing whether or not the pneumatic piston is current active or not. We'll use a boolean variable and set it to false by default. This variable should be defined outside of all functions, below the #include "vex.h"; and using namespace vex; lines of code. //global variables bool pneumaticActive = false; //true or false, whether or not the pnuematic is active Next, we'll make a function that toggles the pneumatic piston on or off. This function flips the pneumaticActive variable first, and then either activates or deactivates the pneumatic based on the value of the pneumaticActive variable. //toggle the pneumatic piston on or off void togglePneumatic() { pneumaticActive = !pneumaticActive; //flip the on/off variable if (pneumaticActive) { Pneumatic.set(true); //Activate the pneumatic } else { Pneumatic.set(false); //Deactivate the pneumatic } } Lastly, we have to set up a callback for the togglePneumatic function, so it is run when a button is pressed. Put the following code in the main function, like so: int main() { //Initializing Robot Configuration. DO NOT REMOVE! vexcodeInit(); //Set up the pneumatic toggle callback Controller1.ButtonX.pressed(togglePneumatic); ​ //there may be more code below, leave it be } That's it! Now you have code that activates and deactivates the pneumatics at the press of a button! Advanced More coding shenanigans Coding Autonomous 12.5% of the match The Autonomous period is only 15 seconds, but it can make a huge difference in matches. In this section, we'll show you how to set up code to run during autonomous. Before we can make the autonomous program, we have to set up the code to interface with the field controllers. That is, when the controller is told to run autonomous during a match, your code needs to recognize that and call the right function. Thus, we'll initialize a Competition variable at the beginning of the main file, after the using namespace vex; line. competition Competition; Next, we'll make a function called autonomousProgram(). This function will contain all of the code that your autonomous will run. void autonomousProgram(void) { //insert autonomous code here } Now, we need to tell the controller that we want this function to run when autonomous starts. To do that, we need to add the line Competition.autonomous(autonomousProgram); immediately after the vexcodeInit() line. int main() { // Initializing Robot Configuration. DO NOT REMOVE! vexcodeInit(); ​ // Set up callback for the autonomous period Competition.autonomous(autonomousProgram); ​ //you may have more code below, leave it there } Now, you can simply put whatever code you would like to run during autonomous in the autonomousProgram() function, and it will run. If you want to have multiple options for autonomous, you can create multiple programs. Coding PIDs Worth it. A PID (proportional integral derivative) controller is an advanced coding technique to make the robot's motion consistent, reliable, and efficient. Theory PIDs are used everywhere in industrial robotics--car factories, robot vacuums, and more. If a robot moves, it likely uses PIDs to move. See these robots? They use PIDs But why? PIDs do one thing, and they do it really well. They move a robot from point A to point B: That's a PID. Yep, it's not that bad. But how? This is where the PID algorithm comes in. There are three parts to a PID controller, given by the acronym. Each part applies a specific power to the drive motors based on certain factors: * P (Proportional): Update motor power based on the present * I (Integral): Update motor power based on the past * D (Derivative): Update motor power based on the future What each part really does The motor power is calculated by the following line of code, which is the heart of the PID algorithm: float motorPower = (kP * proportional) + (kI * integral) + (kD * derviative); That is, each part of the PID is added together to calculate motor power. kP, kI, and kD are constants that determine the relative weights of each portion of the PID. Error Error refers to how far the robot is from the target point. If the robot wants to go forward 20 inches, the PID algorithm would calculate the following errors. Figure 3 Error plays a major factor in the PID algorithm; we'll see how later. If you want some more explanation, here's a good eight-minute video explaining the theory behind PIDs: Now, let's start by coding your drive PID! Drive PID Tutorial In this tutorial, we'll show you how to code a simple drive PID--that is, moving the robot straight forward or backward. We'll use the built-in motor encoders to keep track of how far the robot has gone during the PID loop. First of all, let's create a function called drivePID that accepts an integer variable, called driveDistance. This parameter will dictate how far the robot will go, in degrees (of the drive motors). We'll also have to make this function return the value 0 (this doesn't change anything), due to a small nuance of C++. //Drive PID, drive the robot forward using a PID controller int drivePID(int driveDistance) { //driveDistance is how far the robot should go, in degrees (of the drive motors) ​ return 0; //Keep this line at the end of the function! } This function doesn't do anything yet, but it's a start. From now on, place all of the drive PID code in this function. Remember those constants--kP, kI, and kD--that we mentioned earlier? Those become very important later on, as they make the PID effective on your specific robot. We'll put these constants at the top of the function, for the sake of organization. //PID constants float kP = 0.5; float kI = 0; float kD = 0; You'll determine the specific values of these constants later. Keep in mind that no two robots have the same set of constants, since the weight, speed, and drive friction vary from robot to robot; they affect these constants. Before we get into the actual PID loop, we need to define a few more variables. These variables will be used, along with the PID algorithm, to calculate the motor power that needs to be applied to the drive motors. //Variables for drive PID float error = 0; //how far the robot is from the target float integral = 0; //area under the error vs time graph float derivative = 0; //slope of the error vs time graph float prevError = 0; //the error for the previous iteration of the PID loop ​ //Motor power variables float motorPower = 0; //how much power to apply to the motors, ranging from -1 (backwards at full power) to 1 (forwards at full power) float prevMotorPower = 0; //the motor power for the previous iteration of the PID loop At this point, we'll use a 6-motor drive in our example. We'll calculate how far the robot moves forward by taking the average of all six motor encoders. However, since the robot may have moved before the code reaches this point (from an earlier PID or such), we have to reset the position of the motor encoders back to 0: //Reset motor encoders Right1.setPosition(0, degrees); Right2.setPosition(0, degrees); Right3.setPosition(0, degrees); Left1.setPosition(0, degrees); Left2.setPosition(0, degrees); Left3.setPosition(0, degrees); Now that the setup is done, we can start coding the main PID loop. This loop does the following: 1. 1. 2. Gets the robot's position 3. 2. 4. Calculates the motor power using the PID algorithm 5. 3. 6. Applies the motor power to the drive motors 7. 4. 8. Exits if the robot is close enough to the target position We'll create the outline of the loop, and start by calculating the current distance of the robot. We do this by taking the average position of all six drive motors. If your drive motors are set up differently, adjust your code to take the average of all drive motors or motor groups. while(true) { //Calculate the current distance of the robot and store it as a number (float) float currentDistance = (Right1.position(degrees) + Left1.position(degrees) + Right2.position(degrees) + Left2.position(degrees) + Right3.position(degrees) + Left3.position(degrees)) / 6; ​ wait(20, msec);//don't hog CPU, this stays at the end of the loop } What is currentDistance? From now on, until told otherwise, assume all of the code goes in this while loop, after currentDistance is calculated, but before the wait function is called. The next order of business is to calculate the robot's error--how far it is from the target. This is used to calculate the proportional term of the PID. It's simple: error = driveDistance - currentDistance; //calculate error After that, we have to calculate the integral term. Recall that the integral term nudges the robot the when it's close to the target, so it doesn't stall. However, due to integral windup, we don't want the integral part of the PID to come into play until the robot is close to the target. In this example, we'll only update the integral term when the robot is within 200 degrees of the final position. Since the integral term is simply the area underneath the error vs. time graph, we can simply add the current error to the integral term. Over multiple cycles of the PID loop, it will accumulate and nudge the robot closer to the target. if (error < 200 && error > -200) { integral += error; //updated the integral term if |error| < 200 } Next, we have to find the derivative term. "Derivative" simply means "slope", so we can simply take the difference between the current error and the error in the last iteration of the loop (stored as prevError) to get the derivative term: derivative = error - prevError; //calculate the derivative term At this point, we can code the quintessential line of the PID algorithm! Note that "proportional" is replaced by "error" because the error is directly proportional to how far the robot is from the target. motorPower = (kP * error) + (kI * integral) + (kD * derivative); //calculate motor power Then, we'll clamp the motorPower variable between -1 and 1. We don't want the motors trying to spin at 150% speed. //keep motor power between -1 and 1 if (motorPower > 1) motorPower = 1; if (motorPower < -1) motorPower = -1; One last thing before we can apply the motor power. At present, the PID algorithm will rev up the motors instantaneously at the start of the algorithm. This works, but it can cause the robot to jerk and turn slightly due to the harsh acceleration. We recommend adding a slew rate limiter, which speeds the motors up slowly rather than applying maximum power right at the start. For example, if the slew rate is 0.1, and the loop repeats every 20 milliseconds, then the robot will take 200 milliseconds (10 cycles of the loop) to increase the motor power from 0 to 1. //slew rate limiter float slewRate = 0.1f; if (motorPower > prevMotorPower + slewRate) motorPower = prevMotorPower + slewRate; if (motorPower < prevMotorPower - slewRate) motorPower = prevMotorPower - slewRate; Now, we can apply the refined motorPower variable to the motors. We'll multiply it by 11 because the motor voltage varies from -11 to 11. Left1.spin(forward, 11 * motorPower, volt); Left2.spin(forward, 11 * motorPower, volt); Left3.spin(forward, 11 * motorPower, volt); Right1.spin(forward, 11 * motorPower, volt); Right2.spin(forward, 11 * motorPower, volt); Right3.spin(forward, 11 * motorPower, volt); Next, we need to update the prevError and prevMotorPower variables, so they can be used in the next iteration of the loop. //update "previous" variables prevMotorPower = motorPower; prevError = error; All of the above code, combined, will work. But as of now, the code will keep running forever, even when the robot is at the target. Thus, we need to include a line of code that exits the PID loop once the robot is within 10 degrees of the target. You can change the number 10 to any number you would like; smaller numbers make the PID more precise, but also make it take longer. This code is called the exit condition. //Exit the PID if the robot is within 10 degrees of the target if (error > -10 && error < 10) { break; } That finishes up the code in the while loop. However, the motors may still be turning, even after the PID is done. To account for this, put this code after the while loop but before the end of the drivePID function: //stop the motors when the PID is done Left1.stop(); Left2.stop(); Left3.stop(); Right1.stop(); Right2.stop(); Right3.stop(); And with that, your drive PID code should be done! But, how do you run your PID function? Call the function, passing in the number of degrees (of the drive motors) that you want the robot to go forwards for. Here's an example: drivePID(800); //drive the robot forward 800 degrees drivePID(-500); //drive the robot backwards 500 degrees You can put the above code in your autonomous function. We're not done yet, though--you'll have to tune the PID constants in order to make the PID work well for your specific robot. Turn PID Tutorial In this tutorial, we'll show you how to code a simple turn PID (i.e. the robot turns in place). We'll use an inertial sensor to keep track of the robot's rotation. We'll assume you have already completed the Drive PID tutorial (you should). Thus, some steps will be simplified. Before we get started, let's set up the inertial sensor in your devices tab. We'll name ours "Inertial", Next, make sure you calibrate your inertial sensor in the main function of the robot using this line of code. This line should run when the program starts--make sure the robot is stationary for the first few seconds, so the inertial sensor calibrates correctly. Inertial.calibrate(); Now, the PID! First of all, let's create a function called turnPID that accepts an integer variable, called turnDistance. This variable will tell the robot how far to turn, in degrees. //Turn PID, turn the robot in place using a PID controller int turnPID(int turnDistance) { //driveDistance is how far the robot should turn, in degrees (positive is counterclockwise) ​ return 0; //Keep this line at the end of the function! } This function doesn't do anything yet, but it's a start. From now on, place all of the turn PID code in this function. Next, let's add in our PID constants. //PID constants float kP = 0.05; float kI = 0; float kD = 0; Before we get into the actual PID loop, we need to define a few more variables: //Variables for turn PID float error = 0; //how far the robot is from the target, in degrees float integral = 0; //area under the error vs time graph float derivative = 0; //slope of the error vs time graph float prevError = 0; //the error for the previous iteration of the PID loop ​ //Motor power variables float motorPower = 0; //how much power to apply to the motors, ranging from -1 (clockwise at full power) to 1 (counterclockwise at full power) float prevMotorPower = 0; //the motor power for the previous iteration of the PID loop One last thing--we need to keep track of the inertial sensor's initial position, so we know how far the robot has turned compared to it's rotation before the PID runs. We'll define a variable called startDistance to keep track of this. float startDistance = Inertial.rotation(degrees); Now that the setup is done, we can start coding the main PID loop. We'll start by calculating the current distance of the robot. We do this by taking the difference between the robot's current position and its starting position. while(true) { //Calculate the current distance of the robot and store it as a number (float) float currentDistance = startDistance - Inertial.rotation(degrees); ​ wait(20, msec);//don't hog CPU, this stays at the end of the loop } What is currentDistance? From now on, until told otherwise, assume all of the code goes in this while loop, after currentDistance is calculated, but before the wait function is called. The next order of business is to calculate the robot's error--how far it is from the target. This is used to calculate the proportional term of the PID. error = turnDistance - currentDistance; //calculate error After that, we have to calculate the integral term. We'll only activate it when the robot is within 10 degrees of the target position, to avoid integral windup. if (error < 10 && error > -10) { integral += error; //updated the integral term if |error| < 10 } Next, we have to find the derivative term. "Derivative" means "slope", so we can simply take the difference between the current error and the error in the last iteration of the loop (stored as prevError) to get the derivative term: derivative = error - prevError; //calculate the derivative term At this point, we can add the quintessential line of the PID algorithm! Here it is: motorPower = (kP * error) + (kI * integral) + (kD * derivative); //calculate motor power Then, we'll clamp the motorPower variable between -1 and 1. //keep motor power between -1 and 1 if (motorPower > 1) motorPower = 1; if (motorPower < -1) motorPower = -1; Next, we'll add the slew rate limiter to prevent jerky robot motion. //slew rate limiter float slewRate = 0.1f; if (motorPower > prevMotorPower + slewRate) motorPower = prevMotorPower + slewRate; if (motorPower < prevMotorPower - slewRate) motorPower = prevMotorPower - slewRate; Now, we can apply the refined motorPower variable to the motors. We multiply it by 11 because the motor voltage varies from -11 to 11. Note that the motorPower is multiplied by -11 for the left drive motors, so the robot turns in place instead of driving forward. Left1.spin(forward, -11 * motorPower, volt); Left2.spin(forward, -11 * motorPower, volt); Left3.spin(forward, -11 * motorPower, volt); Right1.spin(forward, 11 * motorPower, volt); Right2.spin(forward, 11 * motorPower, volt); Right3.spin(forward, 11 * motorPower, volt); Next, we need to update the prevError and prevMotorPower variables, so they can be used in the next iteration of the loop. //update "previous" variables prevMotorPower = motorPower; prevError = error; All of the above code, combined, will work. But as of now, the code will keep running forever, even when the robot is at the target. Thus, we need to include a line of code that exits the PID loop once the robot is within 1 degree of the target. Feel free to tune the exit condition, but within 1 degree is a pretty good baseline. //Exit the PID if the robot is within 1 degree of the target if (error > -1 && error < 1) { break; } That finishes up the code in the while loop. However, the motors may still be turning, even after the PID is done. To account for this, put this code after the while loop but before the end of the turnPID function: //stop the motors when the PID is done Left1.stop(); Left2.stop(); Left3.stop(); Right1.stop(); Right2.stop(); Right3.stop(); And with that, your turn PID code is done! We're not finished yet, though--you'll have to tune the PID constants in order to make the PID work well for your specific robot. Tuning PIDs Perseverance makes perfect At this point, you should have coded the PIDs fully. Now, you have to tune those three constants to make the PID work well on your specific robot. Here's a quick recap of each constant: * Proportional (kP): if the robot is far from the target, set the motor power high so the robot gets there faster. If the robot is close, set the motor power low so the robot doesn't overshoot. * Integral (kI): if the robot is close to the target, but not quite there, increase the motor power over time so the robot doesn't stall. * Derivative (kD): if the robot is rapidly approaching the target, apply the brakes so the robot doesn't go too far. Remember, everything on the robot--drivetrain friction, gear ratio, weight distribution, center of gravity--influence the optimal PID values for the robot. That is, you might have to re-adjust the PID values if something major changes on the robot. Let's say we're tuning the drive PID (the process is the same for the turn PID). We started with these values. Try out the drive PID. How well does it work? //PID constants float kP = 0.5; float kI = 0; float kD = 0; Why are kI and kD both 0? If the robot barely moves, try increasing kP--this increases the motor power applied. If the robot jerks forward and goes too far, try decreasing kP. Your goal should be the green line in the graph below, where the robot reached the setpoint (target) quickly and stays there. The graphs represent's the robot's current distance, compared to the target; this applies to both turn PIDs and drive PIDs. Source: OscarLiang.com If your robot acts like the orange line on the graph above, where the robot goes past the target and reverses direction, consider adding in the kD term. As a starting point, set this term to 5 times the value of the kP term. Adding in the integral term (start at about 1/10th the value of kP) may also help. If your robot acts like the blue line on the graph above, where the robot takes a while to reach the target, increase kP or decrease kD. These rest of PID tuning comes down to trial and error; it's your job to find the set of values that works best for your specific robot. If you want a more mathematical approach to estimating kP, kI, and kD from the start, take a look at this page: Ziegler-Nichols Method Advanced coding shenanigins... The Ziegler-Nichols method is a simple way to estimate decent values for kP, kI, and kD. These estimates are a good starting point for manual tuning. We need two numbers before we can run this method: * Ku, the critical (or ultimate) gain * Tu, the period of the oscillations at the critical gain That is, Ku is the minimum value of kP for which the robot will oscillate steadily around the target. To find it, slowly increase kP until the robot wobbles consistently across the target. Then, find Tu by taking a video of the robot oscillating, and find the period, in seconds, of the oscillation. The period is how long it takes the robot to go from one side of the target, to the other side, and then back again. Once you've found Ku and kP, you can then calculate the estimated values of kP, kI, and kD using a few equations, as shown in this PID calculator: Alternate Link: https://html-7159868.codehs.me/pid.html​ ​ A small technicality Graphing PIDs Graphing PIDs can be helpful when tuning them; it gives you a good idea of how quick and accurate the PID is. In the graph below, the green line shows how far the robot is from the target point. The robot starts off far from the target point, but reaches it by the end of the graph. The orange line is the motor power, which initially increases sharply, but then decreases when the robot gets close to the target point so it doesn't overshoot. Here's our simple graph First of all, make sure you include a few libraries at the top of the main file. #include #include #include Next, here's the main graphing function. It clears the brain screen and draws a graph displaying the robot's progress towards the target, and the motor power too. //graphing data, used for PID tuning void graphPID(std::vector errorHistory, std::vector powerHistory, int goal, float error, int time) { //goal is the PID goal (driveDistance) //error history is a list of all of the errors (range is 0 to driveDistance) //powerHistory is a list of the power applied (range is -1 to 1) //error is the current error //time is the current time, in milliseconds //Setup: clear screen and draw the target line Brain.Screen.clearScreen(); Brain.Screen.setPenWidth(2); Brain.Screen.setPenColor(white); Brain.Screen.drawLine(0, 60, 480, 60); Brain.Screen.setPenWidth(1); Brain.Screen.setPenColor(green); ​ //display final error and time Brain.Screen.setCursor(1, 1); Brain.Screen.clearLine(1); Brain.Screen.print(" Final Error: "); Brain.Screen.print(error); Brain.Screen.print(" Time: "); Brain.Screen.print(time); //define the borders of the graph int minY = 60; //error = 0 (robot is at target) int maxY = 230; //error = driveDistance (Robot is at start) int minX = 10; //time = beginning int maxX = 470; //time = end //loop through each data point and graph it for (int i = 0; i < errorHistory.size() - 1; i++) { int x = minX + (maxX - minX) * i / errorHistory.size(); //find the x-value of this data point //graph velocity Brain.Screen.setPenColor(green); Brain.Screen.drawLine(x, minY + (float)errorHistory.at(i) / goal * (maxY - minY), x + (float)(maxX - minX) / errorHistory.size(), minY + (float)errorHistory.at(i + 1) / goal * (maxY - minY)); //graph power, changing color based on direction if (powerHistory.at(i) > 0) { Brain.Screen.setPenColor(orange); } else { Brain.Screen.setPenColor(yellow); } Brain.Screen.drawLine(x, maxY - std::abs(powerHistory.at(i)) * (maxY - minY), x + (float)(maxX - minX) / errorHistory.size(), maxY - std::abs(powerHistory.at(i + 1)) * (maxY - minY)); } } We've made the graphing function; now we just have to call it. But first, we need to log the error history and power history in the PID function. Put this code in the PID function, before the while loop. //lists std::vector errorHistory; //keep track of error over time std::vector powerHistory; //keep track of motor power over time int currentTime = 0; //keep track of time over time (wow!) Next, we'll update the history vectors with the current values, and then call the function. Put this code in the PID function while loop, before the wait(20, msec); line: //update histories and current time errorHistory.push_back(error); powerHistory.push_back(std::abs(motorPower)); currentTime += 20; ​ //graph the PIDs graphPID(errorHistory, powerHistory, driveDistance, error, currrentTime); And with that, you should have a working graph while your PIDs are running! This graph can be used to make tuning the PIDs much easier, as it allows you to see the exact path of the robot to the target point. Tasks Multithreading made simple Tasks allow the code to execute multiple functions simultaneously. For example, one task could handle the driving inputs, and another task could spin a catapult or flywheel at the same time. Tasks themselves are functions that return an integer (it's C++, go along with it). You can put whatever code you want inside of it, but usually there's a while loop so actions within the task execute more than once. Here's a basic task (called myTask) that spins a flywheel forward: int myTask() { while (true) { //do something here Flywheel.spin(forward); //just an example wait(25, msec); } return 0; //C++ technicality } Tasks can be created with this line of code, and will not run until they have been created. The variable spinFlywheel stores the task internally for future reference. task spinFlywheel = task(myTask); If you want the task to stop running, call the stop() function on it: spinFlywheel.stop(); We recommend using tasks for controlling lifts, catapults, or flywheels when the control algorithm required is non-trivial. Advanced Drive Code A more intuitive driving experience While the basic split arcade drive does work, we'll show you a small addition to the code that can make the driving experience more intuitive. This code simply adjusts the turns to be more intense when the robot is going faster. void driveCode() { //drives the robot around based on controller input, double arcade controls //First, get controller inputs int straight = Controller1.Axis3.value(); //gives a number -100 to 100 int turn = Controller1.Axis1.value(); //adjust the turn variable based on the straight one if (forward1 > 50) { turn *= (((forward1 - 50) / 50) + 1); } else if (forward1 < -50) { turn *= (((-50 - forward1) / 50) + 1); } //Calculate proper motor powers int left = straight + turn * 0.7; //the 0.7 makes the turns less intense int right = straight - turn * 0.7; ​ //Spin the drive motors at the calculated velocity Left1.spin(forward, left, percent); Left2.spin(forward, left, percent); Left3.spin(forward, left, percent); Right1.spin(forward, right, percent); Right2.spin(forward, right, percent); Right3.spin(forward, right, percent); } This was adapted from https://wiki.purduesigbots.com/software/competition-specific/curvature-cheesy-drive​ Engineering Notebook Technical documentation The engineering notebook is the pièce de rèsistance of a VEX team. From the engineering notebook, one should be able to follow the entire design process of a team. At a basic level, the notebook should have: * Analysis of the game * Possible designs * Selection of the best design * Step-by-step documentation of the building process * The full code for the robot * Testing and test results * Project management notes In this section, we will be using team 96504C's Spin Up notebook as an example. While this notebook did earn 4 Excellence Awards, it is not a perfect notebook. Still, it's a good starting point. Formatting For the Engineering Notebook There are many programs that can be used to create Engineering Notebooks: Google Docs, Google Slides, Word, Notion, etc. We recommend Google Docs because it is easy to collaborate with others, but any word processor will work. For competitions, print out the notebook and put the pages in a 3-ring binder. Here's an example of a well-formatted notebook page. The green annotations highlight the good aspects of this notebook page Team 96504C's budgeting page. Some ideas adapted from 515R Some of the important elements of every notebook page: * Header / footer with section number * Header / footer with page number * Digital signatures with dates of contribution Additionally, make sure to include a table of contents at the beginning of the notebook, so that it's easy to find sections in the notebook. See the next page, "Notebook Walkthrough" for more information. Notebook Walkthrough Step-by-step notebook guide We'll go through most of the notebook sections you should include, with examples. Every page of the notebook should make it easier for the judges to give your team a perfect score on the notebook rubric. Here's the notebook rubric, for reference: https://roboticseducation.org/documents/2023/06/guide-to-judging.pdf/#page=38&zoom=100,44,62​ ________________ Introductory Pages These should go at the front of your notebook; they organize and propel the rest of the notebook. Title Page The title page should prominently feature the team name, number, and logo (if you have one). This allows the judges to easily identify which notebook is yours and makes it more memorable when they are distributing awards. Simple title page Table of contents The table of contents organizes the rest of the notebook. When appropriate, each entry should be color-coded based on the Engineering Design Process. For example, the game introduction falls under the "ask" step, so it's colored red in the table of contents below. There are a number of ways to format the table of contents itself, but it should be clear when each entry was made and what step of the Engineering Design Process it shows. Example table of contents from team 96504C. Some formatting adopted from team 96504P Engineering Design Process The Engineering Design Process is the essence of VEX Robotics. Thus, a brief description of the process, in the form of a graphic or text, should be included in the notebook. Make sure to cite your sources for images that are taken from another website! Cite your sources! Team Profile After the Engineering design process, you should include a brief description of the team. This helps the judges match faces to teams, and makes your notebook more memorable. For a great example of a team profile (and other good notebook advice), check out https://wiki.purduesigbots.com/team-administration/team-documentation/how-to-start-a-notebook/segments-of-the-notebook#the-team​ Notebook Formatting Next, we recommend including a page about how the notebook is formatted. This should give the judges a basic idea of how the notebook is set up, and allow them to navigate and grade the notebook quickly. Google docs has version history tracking! Use that or something similar to verify dates of contribution Goals The goals section can be very short, but your team should outline a few targets to reach. A few example goals: * Qualifying to States / Worlds * Winning a tournament * Learning a new programming technique * Building a low friction drivetrain GANTT Chart A GANTT chart is a simple, concise, and effective time management tool. It gives a rough outline of how much time should be allocated to each aspect of robotics and demonstrates advanced time management skills. Here's an example early-season GANTT chart: Budget Following 515R's example, we recommend including a budgeting page at the beginning of the notebook. This will help your team to get a realistic estimate of the financial resources necessary to compete at the level you want to. Again, this shows the judges that your team can manage the project diligently and effectively. Why the pie chart? Because it looks nice and conveys information effectively Content Pages These pages make up the bulk of the notebook; they document the designing, building, testing, and refining of the robot and game strategy. Game Analysis The game analysis section has four main goals: 1. 1. 2. Describe the goals of the game and how to score points 3. 2. 4. Document the specifications of field and game elements 5. 3. 6. Discuss the game rules in-depth 7. 4. 8. Determine which game strategies are viable Describe Goals The engineering notebook rubric states that teams must: Identify the game and robot design challenges in detail at the start of each design process cycle with words and pictures. State the goals for accomplishing the challenge Thus, it is important to explicitly lay out the goals for the game. Here's a simple example for VEX Over Under: Document Specifications Next, make sure to identify the dimensions of each field element and game piece. This will come in handy later, during the designing phase. Here's an example of the goal dimensions in Over Under. Discuss Rules After that, describe the specific rules of the game. We recommend giving a broad overview of the scoring and penalty rules, then summarizing each specific game rule. Concise summaries of three specific game rules. Use your words, not the game manual's! Determine Strategies Then, list out some of the potential strategies that might be viable. This will help with the designing of the robot later on, as it shows you which aspects of the game are the most important. We analyzed 7-8 different strategies in Over Under; here's a small snippet: The Advantages / Disadvantages tables are adapted from team 515R's notebook Design Constraints While not technically required by the rubric, adding a short and sweet section on the basic design constraints in VEX adds an element of completeness. Not a complete list, but a good starting point Brainstorming This is where your team generates possible designs for the robot. The Engineering Notebook Rubric states that the notebook should List three or more possible solutions to the challenge with labeled diagrams. Citations provided for ideas that came from outside sources such as online videos or other teams. Each subsystem of the robot should have at least three unique designs, in order to earn full credit on the rubric. Each design should include a full CAD (or at least a detailed drawing), as well as labels for each aspect of the design. Then, explain the design and list the advantages and disadvantages of it. Here's an example page showcasing a possible design for the drivetrain: Give credit where credit is due! Note the small text underneath the table Planning At this point, your team should have analyzed the game and identified three possible designs for each subsystem of the robot. But how do you know which design you should build? That's the purpose of a decision matrix; it determines the best design by comparing each design's strengths and weaknesses. Testing also works, but the decision matrix is more efficient. The Engineering Notebook Rubric says that the notebook must: Explain why the solution was selected through testing and/or a decision matrix. Fully describes the plan to implement the solution. Here's an example of a decision matrix for the drivetrain. Make sure to explain each criteria in the decision matrix. See the page on decision matrices for more information on how to make one. Furthermore, make sure to fully describe the plan to implement the solution. The plan doesn't have to be extremely detailed or complex, but it does have to be there. Building Now, it's time for the fun part! Once you've determined the best design, it's time to build it! According to the Engineering Design Rubric, the notebook should: Record the steps to build and program the solution. Includes enough detail that the reader can follow the logic used by the team to develop their robot design, as well as recreate the robot design from the documentation. That is, the notebook should include enough detail that anyone could re-create the exact robot just from the notebook and the materials used. Label images as much as possible, and make sure to explain every last screw on the robot and why it is there. Here's an example of a page detailing how part of an intake was built: A picture is worth a thousand words It's worth noting that you should also include the full code of the robot after every major revision. When only a small part of the code changes, only include that bit of code, and make sure to describe what changed and why. Here's a small snippet of a main loop, in C++ Example code Testing Does the robot work? Well, there's only one way to find out. Test it! The Engineering Notebook Rubric is very clear; the notebook should Record all the steps to test the solution, including test results. There's a lot of freedom in terms of how you decide test the robot. Of course, the tests should be a valid measure of the effectiveness of the robot or subsystem. Here's an example of a drivetrain test: Short and sweet Tournament Analysis Tournaments are a great way to stress-test the robot under intense gameplay. After each tournament, your team should analyze: * How and why the robot malfunctioned * Number of points scored from each element of the game in each match * Other robot designs and strategies that worked well Here's an example of how to document the problems the robot encountered: Be specific--the purpose of this is to allow you to fix these things later on so it doesn't happen again Here's an example of scoring analysis from Spin Up. Note how we kept track of how we scored points, which allows us to see our strengths and weaknesses. Scoring analysis Here's an example of how to analyze other strategies (for Spin Up): Again, be specific and thorough when analyzing strategy Design Process At some point in every team's season, they will realize that their current robot simply will not do. Then, they are forced to redesign and start from scratch. The Engineering Notebook Rubric is well aware of this fact; one of the requirements is Show that the design process is repeated multiple times to improve performance on a design goal, or robot/game performance. Thus, a redesign has to be properly justified in the notebook. Perhaps the robot needs a faster drivetrain or a smaller chassis, so it can navigate the field faster. Or maybe the other mechanisms on the robot can be replaced with something better. Whatever it is, make sure the notebook explains why the new design will be better than the old one. Here's an example of a redesign justification from Spin Up: Show that the new design is better--because it is! Project Management This part of the notebook is intuitive, but often overlooked or implemented inconsistently. For each meeting, there should be set goals, and the notebook should evaluate whether or not the team met those goals at the end of the meeting. Additionally, the notebook should keep track of time and resource constraints that are relevant to the team. The Engineering Notebook Rubric puts it this way: Provides a complete record of team and project assignments; team meeting notes including goals, decisions, and building/programming accomplishments; Design cycles are easily identified. Resource constraints including time and materials are noted throughout. There are a couple of ways to do this; we recommend setting 2-4 goals per meeting and evaluating the meeting at the end. For example, here's the very first part of a meeting entry: And here's the corresponding summary at the end of the meeting: Note how this notebook also sets a tentative goal for the following meeting--that's time management! Other Notebook Requirements We've covered 90% of the notebook, but there are a couple more requirements to keep in mind (based on the Engineering Notebook Rubric). Here's the first one: Team shows evidence of independent inquiry from the beginning stages of their design process This simply means that teams should take initiative and test their own designs, instead of simply copying from another team online. The next requirement refers to the completeness of the notebook: Records the entire design and development process in such clarity and detail that the reader could recreate the project’s history. That is, every aspect of the designing, building, coding, and testing of the robot should be included in the notebook so well that anybody could build the exact robot using only the notebook as a guide. The last requirement is why all of the example notebook pages have dates and signatures (yes, they were redacted) in the footer of each page: Five (5) points if the notebook has evidence that documentation was done in sequence with the design process. This can take the form of dated entries with the names of contributing students included and an overall system of organization. For example, numbered pages and a table of contents with entries organized for future reference See the "Formatting" article for a good example of how to incorporate digital signatures in the notebook. Conclusion That's it! Follow all of the above steps, and your notebook will shine! Decision Matrices Every choice is a decision matrix Decision Matrices are the best way to make decisions. Which house to buy? Which classes to take? Which college to attend? All of these choices can be analyzed using decision matrices. In Robotics, decision matrices are primarily used to select the best design from multiple candidates. A decision matrix has two lists: * A list of possible designs along the top row * A list of criteria to evaluate the designs along the left column Each design is given a score from 1-5 for each criteria. Then, the weighted total is calculated; it's the sum of each criteria score multiplied by its weight. Criteria: 360 RPM Tank Drive X-Drive Tank Tread Drive Maneuverability Weight: 3 4 5 2 Robustness Weight: 2 4 3 2 Simplicity Weight: 1 5 1 3 Weighted totals: 25 22 13 For example, here's how we calculated the weighted total for the 360 RPM Tank Drive in the above matrix: * Maneuverability: 3 * 4 = 12 * Robustness: 2 * 4 = 8 * Simplicity: 1 * 5 = 5 Weighted total: 12 + 8 + 5 = 25 The other weighted totals are calculated using the same method; the design with the highest weighted total is the best one. ​ Decision Point The point of decision Decision points are critical junctures where choices impact your robot's design and performance. Decision matrices are your trusty tools here. These are key moments where you must choose between different paths, like prioritizing speed or utility. Steps: 1. 1. 2. Identify Decision Points: Recognize moments demanding a choice, e.g., choosing intake mechanism. 3. 2. 4. Create a Decision Matrix: List designs and criteria. For an intake mechanism, criteria could include intake speed, capacity, and distance launched. 5. 3. 6. Evaluate Designs: Rate each design against criteria, considering factors from 1 to 5, with 5 being the best. 7. 4. 8. Calculate Totals: Apply weighting factors to criteria. The design with the highest total score is your choice. It is important to note that when your team comes to a decision point you need to make a decision, otherwise you lose on valuable time. You should allot a certain time frame in the decision making process to set limits on how long you are willing to spend on coming up with a decision to avoid time wastage. If your team is still unable to come up with a decision within the allotted time, it is the captain's job to make the decision. This may sound like it cuts out feedback from other members, but this is the wise choice since there was previously an allotted time where all members could give their input on the choice to make but that didn't result in a consensus. This makes an executive decision the ideal choice to make sure the team's workflow remains on track. ​ Additional Resources Here's some more great resources to help your team get started on the notebook Segments of the Notebook BLRS Wiki Format of an Engineering Notebook VEX Forum ​ Tournaments Trial by fire... Filming Matches But why? You should film every match. Why? Because later, after the tournament, you will: * Analyze why and how the robot broke or malfunctioned * Reflect on your team's game strategy and compare it to other strategies * Study other team's effective robots and game strategies There are 120 seconds in a match--15 for autonomous, 105 for driver control. Examine the videos carefully; did you waste a single second? What can be improved on the robot? Do you need more driver practice? Yes, that's a high standard. That's what it takes to win. Don't waste a single second. Team Interviews The interview is just as important as the notebook for winning judged awards at VEX Tournaments. A good interview is professional, clear, and concise. Interview Tips To ace the interview, you need to know the ins and outs of what they will ask. You can learn more about what the judges will be looking for by checking out Interview Scoring. ⛳ Interview Scoring But, success requires knowing more than just what is on there, it requires knowing how to approach it as well. Here are some interview tips for success: 1. 1. 2. Delegate each teammate to a specific part of the rubric. Doing this allows for a clean organization of who will say what during the interview, and will reduce teammates talking over each other, which can cost you points 3. 2. 4. Not every teammate has to be at the interview. If not all teammates are comfortable with the interview or if you have a big team, not everybody needs to be present at the interview since all present members are expected to contribute meaningfully to the interview process, which can be hard if there are too many or are uncomfortable with it. 5. 3. 6. Focus on what makes you stand out. The interview is also a time to show what makes your team unique from the others, so if you have an unorthodox method of solving a problem make sure to emphasize why you chose that method and why your team uses it. 7. 4. 8. Don't get stressed. Remember, this isn't a job interview where you'll be asked questions you don't know the answer to. This is a robotics interview so everything will be about robotics, so if you know how your robot works you will be fine. 9. 5. 10. Keep track of time since the interview only lasts 10 minutes. You can have a great interview without using all the time but if you run out of time you could potentially miss out on the 8 rubric points given. Be sure to keep a rough outline of how much time you will allot to different components of your robot and design. 11. 6. 12. Don't be afraid to let your personality shine. The interview is your team's chance to stand out from the rest of the competitors and show what is unique about you and your team that the robot can't show. Just make sure you keep it in control and the conversation still covers what is needed for the points in the rubric. Interview Scoring Interviews are scored based on the following rubric, taken from the VEX Judging Guide: Interview Rubric Let's go through each of the categories: 1. 1. Engineering Design Process - The engineering design process is the backbone of robotics and is critical to success. To get a good score, you need to show definitive proof that you used this process in your notebook and you can explain how you used it to make your robot. 2. You can learn more about the engineering design process here: https://vrc-kb.recf.org/hc/en-us/articles/9628278280215-VRC-Engineering-Design-Process​ 3. 2. 4. Game Strategies - To gain this point you need to showcase that you came into this competition with a plan on how you were going to play and what factors affected this plan and how. 5. 3. 6. Robot Design - This one goes a bit hand in hand with the engineering design process and shows that your team actually utilized it in the building of the robot. To get this point, you need to showcase how you got from your initial robot design to your current robot design and how and why the design changed. 7. 4. 8. Robot Build - To gain this point, you have to show that you are knowledgeable about your team's bot and know its ins and outs. To earn this point, you will need to be able to answer any questions the judges might have about your robot's build and parts. 9. 5. 10. Robot Programming - This one follows the same pattern as the build, where you need to be able to explain in depth how your robot's programming works to earn the point. 11. 6. 12. Team and Project Management - To earn this point you need to show that you took measures to keep your team operations on track and managed the project properly to maintain optimal efficiency 13. 7. 14. Teamwork, Communication, Professionalism - To earn this point, your team needs to perform well in the interview itself. This can be done by avoiding talking over one another, communicating clearly with confidence, and being professional. More importantly, every team member must contribute meaningfully to the interview questions being asked. 15. 8. 16. Respect, Courtesy, Positivity - This point comes from your attitude during the interview. If your team is doing the interview with positivity, interest, and respectfulness, you will earn the point. Interview Practice Questions Practice makes perfect To sharpen your team's interview skills, you can try out some practice questions to test if your team is well prepared. This is not an exhaustive list, but it's a good start. Most Common Questions: * What are your roles/jobs on the team? * How did you develop your robot design? * What part of your robot are you most proud of? Why? * Did you use any sensors? What are they used for? * Has your game strategy been effective? How and why? Other Questions: * What does your robot do and how does it score points? * What were the challenges you identified before designing your robot? How did you design your robot to meet those challenges? * Which team members built the robot? * Were there any other robots that inspired your robot design? How? * How do you manage your time? * How do you manage your resources? * What changes did you make to improve your design during the season? * What iteration/version of your robot is this? * What was the most difficult challenge your team has overcome so far? * What problems did you have in working on your robot? How did your team solve them? * If you had one more week to work on your robot, how would you improve it? * How has your strategy changed over the course of the season? * Tell us about your robot’s programming – who was the primary programmer? * What were the challenges of this year’s game that you considered before designing your robot? How did you design your robot to meet those challenges? * What are your goals for Driver and Autonomous Coding Skills scores? What are your average scores? Skills Your path to States and Worlds Skills is perhaps the most important part of any robotics competition, at least for new teams. There are two types of Skills runs: * Driver Skills: The driver gets one minute (1:00) to score as many points as possible on the field * Programming Skills: A program has one minute (1:00) to score as many points as possible on the field At every competition, you get three Skills attempts for each type of run. Your total Skills score is the sum of your best driver run and your best programming run. Even more, get your skills runs in early! Don't wait until the last minute--the line usually gets extra long near the end. But why does it matter? Well, skills rankings are the best indicator of a team's true skill level--that's because the randomness of qualification matches can cause even the best teams to rank poorly. However, Skills is only dependent on your team. Because of this, VEX uses Skills to award qualifications to teams for extra spots at States and Worlds. For example, when there are any extra spots left over in the State tournament, the remaining spots are awarded to the highest unqualified teams on that state's Skills rankings. That means it's relatively easy to qualify to state; you just have to run Skills and do decently well. The same thing applies for Worlds. When a team qualifies twice for Worlds (at States), then the extra Worlds spot is awarded to the highest unqualified team on the States Skill rankings. This is, by far, the best way to qualify to Worlds. At TN States in 2023, all teams that ranked at least 16th in Skills qualified to Worlds. In conclusion, do Skills--you won't regret it. Ranking and Stats Who's the best? In tournaments, VEX Via reports a number of statistics: WP, AP, SP, OPR, DPR, and CCWM. These can seem confusing at first, but we'll go over what each one means here. This is from Haunted 2023 Ranking Stats These determine your overall ranking going into Alliance selection. WP (Win points) Win points are the primary factor when it comes to determining the rankings of a team. Winning a match earns you 2 win points and tying a match earns you 1 win point. Additionally, the Autonomous Win Point (AWP) gives you a single win point. AP (Autonomous points) Autonomous points reflect how many times your team earned the Autonomous bonus in your matches. If two teams have the same number of win points, the team with a higher AP will be higher in the rankings. SP (Strength of schedule points) Strength of schedule points reflect how good your opponents are, since it's the sum of the losing alliance's score for all of your matches. A higher SP means you've faced tougher opponents; for this reason, it's the second tiebreaker if WP and AP are the same. Fun Stats The usefulness of these stats can vary from year to year, but they're always fun to look at. OPR (Offensive power rating) A team's offensive power rating is their calculated contribution their alliance's scores, by a mathematical model. A high OPR means that team is good at scoring points in matches; higher is better. DPR (Defensive power rating) A team's defensive power rating is their calculated contribution the opposing alliance's scores, by a similar mathematical model. A low DPR means that team is good at keeping the opposing alliance's score low; a lower DPR is better. CCWM (Calculated contribution to win margin) A team's CCWM is simply their OPR - DPR. This gives a fairly good estimate to how much they contribute in matches. A team with a high CCWM is good; a team with a low CCWM may have won most of their matches, but perhaps they had good alliance partners. Thus, higher is better. Management Where business and Robotics collide Team Management In order to succeed, a good team is essential. Delegation Delegating team members is crucial to success, productivity, and optimal performance. In a team there are a few roles you can designate to team members: * Captain * Driver * Analyst * Programmer * Designer * Builder * Tester * Notebooker This isn't an exhaustive list of roles, and you can pretty much assign any role to any team member as long as it fits your team's goals and purposes. The roles listed above will exist in some shape or form in every team since every team needs people to perform these tasks. Let's take a look at each of these roles and see what they do: * Captain - The captain manages team operations, ensuring everyone contributes to success. They carry significant responsibility, so choose an experienced, committed member. * Driver - Drives the robot, of course! * Analyst - Analyzing test data and matching observations is vital for team improvement. It guides what to maintain and change. * Programmer - Responsible for robot programming, making it functional and mobile. * Designer - Designing the robot is vital; CAD skills are beneficial. A well-designed robot is crucial for competition success. * Builder - Builders construct the robot based on the designer's plans. * Tester - Conducts experiments, crucial for testing new robot parts. Data collected guides improvements, analyzed by the analyst. * Notebooker - Creating an outstanding engineering notebook is critical, as it can lead to awards like the Design Award, a path to the World Championship in VEX Robotics. How to delegate? Generally, it will be the captain's job to delegate roles to teammates since it is the captain's job to manage team operations. Once again, make sure that your team's captain has the most time to devote to robotics since they will have the most commitment out of anybody else. Drivers should also be decided by a similar category to a captain in that they also need to have a lot of time to devote to the team and should ideally have a bit of prior controller experience. All the other roles should preferably be assigned based on team member preference to make sure teammates are happy with their roles. Otherwise, it will be up to the captain to decide which teammate will have the best performance in which role. Optimal Team Size The optimal team size is 4-5 members. This is the ideal size for team members who have time to commit to robotics. Anything more than 5 starts to result in problems; not every team member can contribute to the team. But, this isn't a steadfast rule because there are times when smaller or larger teams can also work fine. A team of 2-3 members can work if robotics is part of your free time and you are willing to spend numerous hours every single day in the week towards Robotics. A team of 6+ can work if not all team members have enough time to commit to robotics, so more members allow the workload to be lighter on each teammate. Regardless of the size of your team, you need to ask yourself the underlying question: can this team size fulfill the objectives of robotics that have been set aside? If your answer is NO: then you probably need more members so you can complete whatever your objective is. If your answer is YES: then you are good to go! Time Management Time, a clockwork conundrum! Time is always moving and always limited. In Robotics, time management is a crucial part of success, since you always have less time than you think. Thus, it is important to allocate time effectively. Firstly, it's important to create a plan so that your team knows what to expect and when to expect it. A good plan helps your team stay on task and lays out the foundations of what they will be doing for the foreseeable future. One of the ways to establish a good plan is through making a timeline via a GANTT Chart. A GANTT chart outlines the different phases of the design process and details how much time is devoted to each phase. For example, we allocated the first half of May for brainstorming and design, and the second half for prototyping. Here is an example of a Gantt Chart which illustrates a team's timeline from when the competition is announced in May to when the first competition is in August It is important to note that every team's GANTT Chart will be different since every team has their own unique goals that will likely vary from team to team. Setting timely goals is the key to success. Resource Management Truly, your team and your time are your most important resources. But, in this section, we will go over resource management in a different sense--as it relates to physical resources like metal and motors. Label your parts Label all valuable electronic components, so they don't get lost, including: * Batteries * Battery chargers * Brains * Motors Usually, if you lose a battery at a competition but have your team number on it, then some kind soul will return it to your team. This label has saved our battery more than once! Organize your parts Of course! The benefits of organization are obvious; nobody wants to dig around in a box for a few minutes just to find the right screw. But seriously, organize your parts! There are many great, cheap plastic storage containers on Amazon. Many teams also use the Robosource box or heavy duty organizers with wheels. ​ Stuck? That's okay, let's fix it Along the journey of VEX robotics, it's easy to get stuck. Sometimes, your team is waiting on a part to come in, or can't figure out their design, or don't know how to build what they need. This is normal, but it's important to get out of these ruts as soon as possible, since they can stall progress for weeks or even months. Ask yourself the most important question: what is holding your team back from moving on? Based on your answer to the above question, here's some advice from our experience: * Design? Watch robot reveals, matches, tournaments online. See what strategies work, and which ones don't. Ask other teams why they made their robot the way they did, and learn from them. Don't try to design it all yourself--no robot is completely original. * Building? Again, watch robot reveals, pausing the video to see how teams built and supported their mechanisms. CAD helps a ton when building, so invest time into making one. Ask other teams for help, and don't be defensive when offered constructive criticism. * Coding? Keep it simple--the way all good code is. Take a look at our coding tutorials, and if those don't help, ask more experienced teams. Test things one step at a time, and find where the code went wrong. * Team dynamics? When team members disagree, it's nearly impossible to make progress. All disagreements come down to a difference in perspective--some people value good notebooks, some value original designs, some value what works in matches. Talk out your differences, find the root cause of the schism, and remember that you are all working towards the same ultimate goal. The best option is usually compromise between the two perspectives in question. ​ Physics Physics works! Physics is the study of the motion and nature of objects. Obviously, this plays a huge role in Robotics. One of the primary concepts from physics is the idea of force. At a base level, a force is a push or pull that makes an object change direction. * The wheels of the robot apply a force on the ground, which pushes the robot forward * Rubber bands impart force on a catapult arm, causing it to slam upward * An intake exerts a force on a game object, making it move in a different direction The two most important applications of force are torque and stress forces. Torque is simply rotational force, and stress forces are internal to the robot. Torque What is Torque? Torque is a vector which means its has a magnitude and a direction. At its most basic level is a measure of the force that can cause an object to rotate about an axis. Just like force causes an object to accelerate in linear kinematics torque causes an object to accelerate in angular kinematics How do we calculate torque? The formula to calculate the magnitude of torque is given as: ​ �=�∗����(�) τ=F∗dsin(θ) where: * τ is the torque * F is the force applied to the rotating object * d is the distance of the applied force from the point of rotation * θ is the angle of the applied vector force in relation to the rotating arm. This arm is also known as the moment arm The concept of torque is essential in robotics as it is a fundamental of motors, gears, and levers which are used to transmit power and motion. To drive the robot you need to torque to accelerate, hold a top speed and to push other opponents. It is also needed to lift heavier objects faster and while keeping the speed of the robot. Torque Calculator If you can't figure out what θ should be, it's probably 90 degrees Alternate Link: https://html-7159868.codehs.me/torque.html​ ​ Gear Ratios Gears are obviously a very important part of how a robot moves and its functions work, however when using gears calculations have to made to determine the gear ratio. As shown in the example below, there is usually one gear driving and then the rest are driven by that gear. In this scenario like many there is one smaller gear and another larger one. ​ The gears in VEX are always made in proportion to the number of teeth. The ratio of the teeth in each gear is known as the gear ratio and this is determined based on the ratio of speed to torque that is needed. With gears the speed and torque are inversely related. As shown in the diagram, when the driving gear is larger (has more teeth) than the driven gear the speed is increased however the torque is decrease. The same is true vice versa. When the smaller gear is driving, the torque is increased and the speed is decreased. This ratio is calculated using the following formula: GEAR RATIO = (TEETH OF DRIVING GEAR) / (TEETH OF DRIVEN GEAR) If the ratio is between 0 and 1, then the gear system has a torque advantage, but if the gear ratio is greater than 1, it has a speed advantage. Having a good balance between speed and torque is an important part of VEX Robotics. ​ ​ Stress Forces In robotics the concept of forces is essential to understand to limit the damage to your robot in competition. In VEX robotics there are 3 common stress forces: Bending, Torsion, Compression/Tension. Bending is the most common of the stress forces and it comes when a force is applied perpendicular to the length of the object. This is most common in lifts Torsion can be common in underdeveloped robots. Torsion happens when a piece of metal (usually a long piece) is twisted. This is most common when sparsely supported metals are involved in high torque situations Compression/Tension are opposing pushing(compression) or pulling(tension) forces that are often seen at connections between pieces through screws, standoffs, or spacers that become inconsistent over time. When a metal is subject to stress, it it can deform either elastically (temporarily) or plastically (permanently). If the metal breaks it is known as yielding or failure. Stress can also affect the properties of the metal like the ductility, malleability, and toughness. This means that if the metal undergoes stress it will be less able to withstand further stress. Ways to combat this stress include applying appropriate protective coatings and designing structures to distribute stress evenly. Extra stuff 96504 Gallery Fun pictures... String! We don't talk about our Spin Up intake We shot through their robot and won by 2 points This is why we box Forge your own path. Or, in this case, your own hole 27/28. If you know, you know Sacrifices have to be made... Clear! Don't overthink it. ​ VEX Team Resources (Over Under) We are here to help Primary Resources Game video: https://www.youtube.com/watch?v=dvDqEI7qO34​ Game Manual (READ THIS!): https://www.vexrobotics.com/over-under-manual​ "How to Win Robotics" - a document giving an overview of the process of Robotics, made by a former club member: https://docs.google.com/document/d/1ss3dj3vwZIJbd0fW2elEkKdIoimpplIeJ7vIDK2Wzq0​ "101 Things I Wish I'd known..." - another overview of VEX robotics, with good general advice: https://www.vexforum.com/t/101-things-i-wish-id-known-before-my-first-vex-tournament/16081​ "VEX Notebooking Guide" - explains the Engineering Design Notebook well: https://docs.google.com/document/d/1_Q3tK04eIctlpk9GPR97G4Y_mjCfG2P7fL3U60Ilepc/edit?usp=sharing​ Over Under Robot Designs Finals match from the first major VEX tournament (MOA). This is great for getting an idea of how this game is played at a high level by other teams: https://www.youtube.com/watch?v=sYvphItqic0​ #1 Skills run in the World (as of 9/5/23). Skills is how you qualify to States and Worlds! https://www.youtube.com/watch?v=HOCC7GQ2VHM​ Peruse this page if you please: https://www.youtube.com/results?search_query=vex+over+under​ ________________ Please note that the rest of this website is a work in progress (as of 10/23/23) and will be updated throughout the semester. Driving Simulator Want to test out how it feels to drive your robot design before you build it? We made a driving simulator with fairly accurate physics, so you can get a feel for different drivetrains. VEX V5 C++ API Namespaces this_thread Classes class __tridevice Use this class to get access to Three Wire Port functions and members. More... class accelerometer Use this class when programming with an accelerometer sensor. More... class analog_in Use this class when programming with an analog-in device. More... class bitmap Bitmap image. More... class brain Use the brain class to see battery information, SD card information, or write to the Screen. More... class bumper Use this class when programming with the bumper device. More... class color Use the color class to create Color objects. More... class competition Use this class to set up your program for competitions. More... class controller Use the controller class to get values from the remote controller as well as write to the controller's screen. More... class device Use the device class to get information about a vex device plugged into the V5. More... class devices Use the device class to get information about all of the vex devices plugged into the V5. More... class digital_in Use this class when programming with a digital-in device. More... class digital_out Use this class when programming with a digital-out device. More... class distance Use the distance class to control the distance sensor. More... class drivetrain class encoder Use this class when programming with an encoder. More... class guido class gyro Use this class when programming with a gyro sensor. More... class inertial Use the inertial class to control the inertial sensor. More... class led Use this class when programming with a led device. More... class light Use this class when programming with a light sensor. More... class limit Use this class when programming with the limit switch. More... class line Use this class when programming with a line follower. More... class motor Use the motor class to control motor devices. More... class motor29 Use this class when programming a motor connected to a motor controller 29. More... class motor_group class motor_victor Use this class when programming with a motor connected to a victor motor controller. More... class mutex Use this class to create and control mutexes. More... class optical Use the optical class to control the optical sensor. More... class pneumatics Use this class when programming with a pneumatics device. More... class pot Use this class when programming with a potentiometer. More... class pwm_out Use this class when programming with a pwm-out device. More... class rotation Use the rotation class to control absolute encoder devices. More... class safearray class servo Use this class when programming with a servo device. More... class smartdrive class sonar Use this class when programming with a sonar sensor. More... class thread Use this class to create and control threads. More... class timer Use the timer class to create timers for your program. More... class triport Use this class to get and set information about devices on 3-wire ports. More... class vision Use this class when programming the vision sensor. More... Enumerations enum turnType { turnType::left = 0, turnType::right = 1, turnType::undefined = 0xFF } enum percentUnits { percentUnits::pct = 0 } The measurement units for percentage values. More... enum timeUnits { timeUnits::sec, timeUnits::msec } The measurement units for time values. More... enum currentUnits { currentUnits::amp } The measurement units for current values. More... enum voltageUnits { voltageUnits::volt, voltageUnits::mV } The measurement units for voltage values. More... enum powerUnits { powerUnits::watt } The measurement units for power values. More... enum torqueUnits { torqueUnits::Nm, torqueUnits::InLb } The measurement units for torque values. More... enum rotationUnits { rotationUnits::deg, rotationUnits::rev, rotationUnits::raw = 99 } The measurement units for rotation values. More... enum velocityUnits { velocityUnits::pct = (int)percentUnits::pct, velocityUnits::rpm, velocityUnits::dps } The measurement units for velocity values. More... enum distanceUnits { distanceUnits::mm, distanceUnits::in, distanceUnits::cm } The measurement units for distance values. More... enum analogUnits { analogUnits::pct = (int)percentUnits::pct, analogUnits::range8bit, analogUnits::range10bit, analogUnits::range12bit, analogUnits::mV } The measurement units for analog values. More... enum temperatureUnits { temperatureUnits::celsius, temperatureUnits::fahrenheit, temperatureUnits::pct = 0xFF } The measurement units for temperature values. More... enum directionType { directionType::fwd = 0, directionType::rev, directionType::undefined } The defined units for direction values. More... enum brakeType { brakeType::coast = kV5MotorBrakeModeCoast, brakeType::brake = kV5MotorBrakeModeBrake, brakeType::hold = kV5MotorBrakeModeHold, brakeType::undefined } The defined units for brake values. More... enum gearSetting { gearSetting::ratio36_1 = kMotorGearSet_36, gearSetting::ratio18_1 = kMotorGearSet_18, gearSetting::ratio6_1 = kMotorGearSet_06 } The defined units for gear values. More... enum fontType { fontType::mono20 = 0, fontType::mono30, fontType::mono40, fontType::mono60, fontType::prop20, fontType::prop30, fontType::prop40, fontType::prop60, fontType::mono15, fontType::mono12, fontType::chinese16 = 0xf0 } The defined units for font values. More... enum triportType { triportType::analogInput, triportType::analogOutput, triportType::digitalInput, triportType::digitalOutput, triportType::button, triportType::potentiometer, triportType::lineSensor, triportType::lightSensor, triportType::gyro, triportType::accelerometer, triportType::motor, triportType::servo, triportType::quadEncoder, triportType::sonar, triportType::motorS } The defined units for triport devices. More... enum controllerType { controllerType::primary = kControllerMaster, controllerType::partner = kControllerPartner } The defined units for controller devices. More... enum axisType { axisType::xaxis, axisType::yaxis, axisType::zaxis } The defined units for inertial sensor axis. More... enum orientationType { orientationType::roll, orientationType::pitch, orientationType::yaw } The defined units for inertial sensor orientation. More... enum sizeType { sizeType::none, sizeType::small, sizeType::medium, sizeType::large } The defined units for distance sensor object size. More... enum ledState { ledState::off, ledState::on } The defined units for optical sensor led state. More... Functions void wait (double time, timeUnits units=timeUnits::sec) Wait for a specific amount of time. Identical to sleep() More... void sleep (double duration, timeUnits units=timeUnits::sec) Wait for a specific amount of time. Identical to wait() More... void sleepMs (uint32_t duration) Wait for a specific amount of time (in milliseconds) More... double clock () System time, in seconds. More... uint32_t clockMs () System time, in milliseconds. More... uint64_t clockUs () System time, in microseconds. More... Variables const rotationUnits degrees const rotationUnits turns const percentUnits percent const timeUnits seconds const distanceUnits inches const distanceUnits mm const directionType forward const directionType reverse const turnType left const turnType right const axisType xaxis const axisType yaxis const axisType zaxis const orientationType roll const orientationType pitch const orientationType yaw const fontType monoM const fontType monoL const fontType monoXL const fontType monoXXL const fontType monoS const fontType monoXS const fontType propM const fontType propL const fontType propXL const fontType propXXL const controllerType primary const controllerType partner const char * rumbleLong const char * rumbleShort const char * rumblePulse const int32_t PORT1 const int32_t PORT2 const int32_t PORT3 const int32_t PORT4 const int32_t PORT5 const int32_t PORT6 const int32_t PORT7 const int32_t PORT8 const int32_t PORT9 const int32_t PORT10 const int32_t PORT11 const int32_t PORT12 const int32_t PORT13 const int32_t PORT14 const int32_t PORT15 const int32_t PORT16 const int32_t PORT17 const int32_t PORT18 const int32_t PORT19 const int32_t PORT20 const int32_t PORT21 const int32_t PORT22 const percentUnits pct const timeUnits sec const timeUnits msec const voltageUnits volt const currentUnits amp const powerUnits watt const torqueUnits Nm const torqueUnits InLb const rotationUnits deg const rotationUnits rev const velocityUnits rpm const velocityUnits dps const temperatureUnits celsius const temperatureUnits fahrenheit const directionType fwd const brakeType coast const brakeType brake const brakeType hold const gearSetting ratio36_1 const gearSetting ratio18_1 const gearSetting ratio6_1 const color & black const color & white const color & red const color & green const color & blue const color & yellow const color & orange const color & purple const color & cyan const color & transparent const fontType mono20 const fontType mono30 const fontType mono40 const fontType mono60 const fontType mono15 const fontType mono12 const fontType prop20 const fontType prop30 const fontType prop40 const fontType prop60 const analogUnits range8bit const analogUnits range10bit const analogUnits range12bit const analogUnits mV Detailed Description device class Vision sensor device class. Triport device class. All devices class. base interface class used with IMU and gyro a safe array template Enumeration Type Documentation ◆ turnType enum vex::turnType strong Enumerator left right undefined ◆ percentUnits enum vex::percentUnits strong The measurement units for percentage values. Enumerator pct A percentage unit that represents a value from 0% to 100%. ◆ timeUnits enum vex::timeUnits strong The measurement units for time values. Enumerator sec A time unit that is measured in seconds. msec A time unit that is measured in milliseconds. ◆ currentUnits enum vex::currentUnits strong The measurement units for current values. Enumerator amp A current unit that is measured in amps. ◆ voltageUnits enum vex::voltageUnits strong The measurement units for voltage values. Enumerator volt A voltage unit that is measured in volts. mV The measurement units for power values millivolts. ◆ powerUnits enum vex::powerUnits strong The measurement units for power values. Enumerator watt A power unit that is measured in watts. ◆ torqueUnits enum vex::torqueUnits strong The measurement units for torque values. Enumerator Nm A torque unit that is measured in Newton Meters. InLb A torque unit that is measured in Inch Pounds. ◆ rotationUnits enum vex::rotationUnits strong The measurement units for rotation values. Enumerator deg A rotation unit that is measured in degrees. rev A rotation unit that is measured in revolutions. raw A rotation unit that is measured in raw data form. ◆ velocityUnits enum vex::velocityUnits strong The measurement units for velocity values. Enumerator pct A velocity unit that is measured in percentage. rpm A velocity unit that is measured in rotations per minute. dps A velocity unit that is measured in degrees per second. ◆ distanceUnits enum vex::distanceUnits strong The measurement units for distance values. Enumerator mm A distance unit that is measured in millimeters. in A distance unit that is measured in inches. cm A distance unit that is measured in centimeters. ◆ analogUnits enum vex::analogUnits strong The measurement units for analog values. Enumerator pct An analog unit that is measured in percentage. range8bit An analog unit that is measured in an 8-bit analog value (a value with 256 possible states). range10bit An analog unit that is measured in a 10-bit analog value (a value with 1024 possible states). range12bit An analog unit that is measured in a 12-bit analog value (a value with 4096 possible states). mV An analog unit that is measured in millivolts. ◆ temperatureUnits enum vex::temperatureUnits strong The measurement units for temperature values. Enumerator celsius A temperature unit that is measured in degrees Celsius. fahrenheit A temperature unit that is measured in degrees Fahrenheit. pct A temperature unit that is measured in percentage of allowed range. ◆ directionType enum vex::directionType strong The defined units for direction values. Enumerator fwd A direction unit that is defined as forward. rev A direction unit that is defined as backward. undefined ◆ brakeType enum vex::brakeType strong The defined units for brake values. Enumerator coast A brake unit that is defined as coast. brake A brake unit that is defined as brake. hold A brake unit that is defined as hold. undefined ◆ gearSetting enum vex::gearSetting strong The defined units for gear values. Enumerator ratio36_1 A gear unit that is defined as the red 36:1 gear cartridge used in V5 Smart Motors. ratio18_1 A gear unit that is defined as the green 18:1 gear cartridge used in V5 Smart Motors. ratio6_1 A gear unit that is defined as the blue 6:1 gear cartridge used in V5 Smart Motors. ◆ fontType enum vex::fontType strong The defined units for font values. Enumerator mono20 A font unit that is defined as mono20. mono30 A font unit that is defined as mono30. mono40 A font unit that is defined as mono40. mono60 A font unit that is defined as mono60. prop20 A font unit that is defined as prop20. prop30 A font unit that is defined as prop30. prop40 A font unit that is defined as prop40. prop60 A font unit that is defined as prop60. mono15 A font unit that is defined as mono15. mono12 A font unit that is defined as mono12. chinese16 A font supporting Chinese characters. ◆ triportType enum vex::triportType strong The defined units for triport devices. Enumerator analogInput A triport unit that is defined as an analog input. analogOutput A triport unit that is defined as an analog output. digitalInput A triport unit that is defined as a digital input. digitalOutput A triport unit that is defined as a digital output. button A triport unit that is defined as a button. potentiometer A triport unit that is defined as a potentiometer. lineSensor A triport unit that is defined as a line sensor. lightSensor A triport unit that is defined as a light sensor. gyro A triport unit that is defined as a gyro. accelerometer A triport unit that is defined as an accelerometer. motor A triport unit that is defined as a motor. servo A triport unit that is defined as a servo. quadEncoder A triport unit that is defined as a quadrature encoder. sonar A triport unit that is defined as a sonar. motorS A triport unit that is defined as a motor with slew rate control. ◆ controllerType enum vex::controllerType strong The defined units for controller devices. Enumerator primary A controller unit defined as a primary controller. partner A controller unit defined as a partner controller. ◆ axisType enum vex::axisType strong The defined units for inertial sensor axis. Enumerator xaxis yaxis zaxis ◆ orientationType enum vex::orientationType strong The defined units for inertial sensor orientation. Enumerator roll pitch yaw ◆ sizeType enum vex::sizeType strong The defined units for distance sensor object size. Enumerator none small medium large ◆ ledState enum vex::ledState strong The defined units for optical sensor led state. Enumerator off on Function Documentation ◆ wait() void vex::wait ( double time, timeUnits units = timeUnits::sec ) Wait for a specific amount of time. Identical to sleep() Parameters time The length of time to wait units The units of time (default seconds) ◆ sleep() void vex::sleep ( double duration, timeUnits units = timeUnits::sec ) Wait for a specific amount of time. Identical to wait() Parameters duration The length of time to wait units The units of time (default seconds) ◆ sleepMs() void vex::sleepMs ( uint32_t duration ) Wait for a specific amount of time (in milliseconds) Parameters duration The length of time to wait (in milliseconds) ◆ clock() double vex::clock ( ) System time, in seconds. ◆ clockMs() uint32_t vex::clockMs ( ) System time, in milliseconds. ◆ clockUs() uint64_t vex::clockUs ( ) System time, in microseconds. Variable Documentation ◆ degrees const rotationUnits vex::degrees ◆ turns const rotationUnits vex::turns ◆ percent const percentUnits vex::percent ◆ seconds const timeUnits vex::seconds ◆ inches const distanceUnits vex::inches ◆ mm const distanceUnits vex::mm ◆ forward const directionType vex::forward ◆ reverse const directionType vex::reverse ◆ left const turnType vex::left ◆ right const turnType vex::right ◆ xaxis const axisType vex::xaxis ◆ yaxis const axisType vex::yaxis ◆ zaxis const axisType vex::zaxis ◆ roll const orientationType vex::roll ◆ pitch const orientationType vex::pitch ◆ yaw const orientationType vex::yaw ◆ monoM const fontType vex::monoM ◆ monoL const fontType vex::monoL ◆ monoXL const fontType vex::monoXL ◆ monoXXL const fontType vex::monoXXL ◆ monoS const fontType vex::monoS ◆ monoXS const fontType vex::monoXS ◆ propM const fontType vex::propM ◆ propL const fontType vex::propL ◆ propXL const fontType vex::propXL ◆ propXXL const fontType vex::propXXL ◆ primary const controllerType vex::primary ◆ partner const controllerType vex::partner ◆ rumbleLong const char* vex::rumbleLong ◆ rumbleShort const char* vex::rumbleShort ◆ rumblePulse const char* vex::rumblePulse ◆ PORT1 const int32_t vex::PORT1 ◆ PORT2 const int32_t vex::PORT2 ◆ PORT3 const int32_t vex::PORT3 ◆ PORT4 const int32_t vex::PORT4 ◆ PORT5 const int32_t vex::PORT5 ◆ PORT6 const int32_t vex::PORT6 ◆ PORT7 const int32_t vex::PORT7 ◆ PORT8 const int32_t vex::PORT8 ◆ PORT9 const int32_t vex::PORT9 ◆ PORT10 const int32_t vex::PORT10 ◆ PORT11 const int32_t vex::PORT11 ◆ PORT12 const int32_t vex::PORT12 ◆ PORT13 const int32_t vex::PORT13 ◆ PORT14 const int32_t vex::PORT14 ◆ PORT15 const int32_t vex::PORT15 ◆ PORT16 const int32_t vex::PORT16 ◆ PORT17 const int32_t vex::PORT17 ◆ PORT18 const int32_t vex::PORT18 ◆ PORT19 const int32_t vex::PORT19 ◆ PORT20 const int32_t vex::PORT20 ◆ PORT21 const int32_t vex::PORT21 ◆ PORT22 const int32_t vex::PORT22 ◆ pct const percentUnits vex::pct ◆ sec const timeUnits vex::sec ◆ msec const timeUnits vex::msec ◆ volt const voltageUnits vex::volt ◆ amp const currentUnits vex::amp ◆ watt const powerUnits vex::watt ◆ Nm const torqueUnits vex::Nm ◆ InLb const torqueUnits vex::InLb ◆ deg const rotationUnits vex::deg ◆ rev const rotationUnits vex::rev ◆ rpm const velocityUnits vex::rpm ◆ dps const velocityUnits vex::dps ◆ celsius const temperatureUnits vex::celsius ◆ fahrenheit const temperatureUnits vex::fahrenheit ◆ fwd const directionType vex::fwd ◆ coast const brakeType vex::coast ◆ brake const brakeType vex::brake ◆ hold const brakeType vex::hold ◆ ratio36_1 const gearSetting vex::ratio36_1 ◆ ratio18_1 const gearSetting vex::ratio18_1 ◆ ratio6_1 const gearSetting vex::ratio6_1 ◆ black const color& vex::black ◆ white const color& vex::white ◆ red const color& vex::red ◆ green const color& vex::green ◆ blue const color& vex::blue ◆ yellow const color& vex::yellow ◆ orange const color& vex::orange ◆ purple const color& vex::purple ◆ cyan const color& vex::cyan ◆ transparent const color& vex::transparent ◆ mono20 const fontType vex::mono20 ◆ mono30 const fontType vex::mono30 ◆ mono40 const fontType vex::mono40 ◆ mono60 const fontType vex::mono60 ◆ mono15 const fontType vex::mono15 ◆ mono12 const fontType vex::mono12 ◆ prop20 const fontType vex::prop20 ◆ prop30 const fontType vex::prop30 ◆ prop40 const fontType vex::prop40 ◆ prop60 const fontType vex::prop60 ◆ range8bit const analogUnits vex::range8bit ◆ range10bit const analogUnits vex::range10bit ◆ range12bit const analogUnits vex::range12bit ◆ mV const analogUnits vex::mV ________________ Functions int32_t get_id () Gets the ID of the thread. More... void yield () Suspends the current thread. More... void sleep_for (uint32_t time_ms) sleep_for More... void sleep_until (uint32_t time) sleep_until More... void setPriority (int32_t priority) Sets the priority of the current thread. More... int32_t priority () Gets the priority of the current thread. More... Function Documentation ◆ get_id() int32_t vex::this_thread::get_id ( ) Gets the ID of the thread. Returns Returns an integer that represents the thread's ID. ◆ yield() void vex::this_thread::yield ( ) Suspends the current thread. ◆ sleep_for() void vex::this_thread::sleep_for ( uint32_t time_ms ) sleep_for Suspends the current thread until the time is expired in milliseconds. Parameters time_ms The amount of time for the thread to sleep. ◆ sleep_until() void vex::this_thread::sleep_until ( uint32_t time ) sleep_until Sleeps until the system timer reaches the time specified in the parameter. Parameters time The amount of time for the thread to sleep. ◆ setPriority() void vex::this_thread::setPriority ( int32_t priority ) Sets the priority of the current thread. Parameters priority The priority of the thread to be set to. ◆ priority() int32_t vex::this_thread::priority ( ) Gets the priority of the current thread. Returns Returns the priority of the current thread as an integer. ________________ Full Spin Up Code /*----------------------------------------------------------------------------*/ /* */ /* Module: main.cpp */ /* Author: VEX */ /* Created: Thu Sep 26 2019 */ /* Description: Competition Template */ /* */ /*----------------------------------------------------------------------------*/ // ---- START VEXCODE CONFIGURED DEVICES ---- // Robot Configuration: // [Name] [Type] [Port(s)] // Controller1 controller // Flywheel motor_group 1, 2 // LeftMotors motor_group 3, 4 // RightMotors motor_group 5, 6 // RightEncoder encoder A, B // LeftEncoder encoder C, D // BackEncoder encoder E, F // Intake motor 7 // Indexer motor 8 // Wings digital_out G // Optical optical 9 // VisionSensor vision 10 // Inertial1 inertial 19 // Inertial2 inertial 20 // LineTracker line H // Motor motor 11 // ---- END VEXCODE CONFIGURED DEVICES ---- //neccessary stuff #include "vex.h" #include #include #include #include using namespace vex; competition Competition; //global variables int flywheelLastPos = 0; //the last position of the flywheel in degrees, based on the internal motor encoders int flywheelTargetRPM = 1800; //the target RPM of the flywheel bool flywheelOn = false; //true or false, whether or not the flywheel is on right now bool auton = false; //whether or not the robot is being controlled autonomously float driveSpeed = 1.0f; //driving (forward and backward) speed of the robot float turnSpeed = .7f; //turning speed of the robot int drawMode = 0; //what to draw on the brain screen? 0: flywheel 1: PID 2: vision sensor 3: status update 4: odom int tempDrawMode = 0; //store the previous draw mode temporarily bool useTBH = true;//controls how the flywheel speed is updated int overHeatingTimer = 0; //keeps track of how often to display an overheating warning bool firstCross = false; //whether or not the first cross of the target RPM line has occured yet int autonType = 1; //the type of autonomous to use float driveDistance = 0; //drive distnace for drive PID bool opticalMode = false;//whether or not the optical sensor dictates when discs are shot. double gain = 0.000143; //was 0.00013 before, the gain variable for TBH velocity control double defaultGain = 0.000143; //the default gain, was .000143 bool visionAlign = false; //whether or not to align to the goal using the vision sensor bool visionTrackRed = true; //whether or not to track red objects as the goal bool visionTrackBlue = true; //whether or not to track blue objects as the goal float speedPID = 1; // the speed to run the motors at in PID loops, range is0-1 bool tripleShooting = false; //whether or not a triple shot is active float motorPowerApprox = 0.61; //default guess for the motor power, for 1800 rpm, for the flywheel //odometry constants float pos[2] = {0, 0}; //x and y global position of the robot float angle = 0; //the angle of the robot relative to the starting angle, in radians float sideWheelRadius = 4.8258328 * 3633.0 / 3600; //in inches, the distance between each side wheel and the tracking center, 4.8125 //above, it was 4.8623 for the first half of the second week of summer camp float backWheelRadius = 1; //in inches, the distance between the back wheel and the tracking center int prevLeftEncoder = 0;//the previous reading of the left encoder, in degrees int prevRightEncoder = 0;//the previous reading of the right encoder, in degrees int prevBackEncoder = 0; //the previous reading of the back encoder, in degrees //helper functions void printController(float i) { //prints a number to the controller console (very handy for debugging) Controller1.Screen.clearLine(3); Controller1.Screen.setCursor(3, 1); Controller1.Screen.print(i); } void printControllerSetup() { //sets up the controller to be printed on Controller1.Screen.clearLine(3); Controller1.Screen.setCursor(3, 1); } //graphing data, used for flywheel velocity control void graphFlywheelVelocity(std::vector velocityHistory, std::vector powerHistory) { //Given some data, display a graph showing the current velocity and voltage draw of the flywheel motor //the velocity history is a list of integers (range: 0-the maximum flywheel speed) that is the current speed of the flywheel, in RPM //the power history is a list of integers (range: 0-100) that is the percentage amount representing how much power the motors applied. //For example, if the motor was spun at half power at a certain point in time, this corresponding value would be 50 //setup: clear screen and draw the target line Brain.Screen.clearScreen(); Brain.Screen.setPenWidth(2); Brain.Screen.setPenColor(white); Brain.Screen.drawLine(0, 60, 480, 60); Brain.Screen.setPenWidth(1); Brain.Screen.setPenColor(green); //also display some helpful information on the top of the brain screen Brain.Screen.setCursor(1, 1); Brain.Screen.clearLine(1); Brain.Screen.print(Flywheel.current()); Brain.Screen.print(" Amperes "); Brain.Screen.print(Flywheel.velocity(rpm) * 5); //times 5 to account for the gear ratio of the flywheel Brain.Screen.print(" RPM "); Brain.Screen.print(Flywheel.voltage()); Brain.Screen.print(" Volts "); //establish parameters that determine where the graph is drawn on the screen //for y, bottom (0) is 215 and top (100) is 60 int minY = 60; int maxY = 230; //for x, start at 10 and end at 470, so don't draw the graph within 10px of the border int minX = 10; int maxX = 470; //horizontalScale adjusts how much of the graph to draw on the screen (ex: last 3 seconds or last 10 seconds) float horizontalScale = 400; //loop through every data point and draw a line between it and the next one, to create a smooth graph. for (int i = std::max((int)velocityHistory.size() - (int)horizontalScale, 0); i < velocityHistory.size() - 1; i++) { //calculate where to draw this part of the graph int x = maxX - (maxX - minX) * (velocityHistory.size() - i) / horizontalScale; //graph velocity Brain.Screen.setPenColor(green); Brain.Screen.drawLine(x, maxY - (float)velocityHistory.at(i) / flywheelTargetRPM * (maxY - minY), x + (float)(maxX - minX) / horizontalScale, maxY - (float)velocityHistory.at(i + 1) / flywheelTargetRPM * (maxY - minY)); //graph power Brain.Screen.setPenColor(orange); Brain.Screen.drawLine(x, maxY - powerHistory.at(i) / 100.0f * (maxY - minY), x + (float)(maxX - minX) / horizontalScale, maxY - powerHistory.at(i + 1) / 100.0f * (maxY - minY)); } } //graphing data, used for PID tuning void graphPID(std::vector errorHistory, std::vector powerHistory, int goal, float error, int time) { //goal is the PID goal //error history is a list of all of the errors //powerHistory is -1 to 1 of the power applied //setup: clear screen and draw the target line Brain.Screen.clearScreen(); Brain.Screen.setPenWidth(2); Brain.Screen.setPenColor(white); Brain.Screen.drawLine(0, 60, 480, 60); Brain.Screen.setPenWidth(1); Brain.Screen.setPenColor(green); //also display amps Brain.Screen.setCursor(1, 1); Brain.Screen.clearLine(1); Brain.Screen.print(" Final Error: "); Brain.Screen.print(error); Brain.Screen.print(" Time: "); Brain.Screen.print(time); //y positions //bottom (0) is 215 //top (100) is 60 //above (110) (overshoot) is <60 int minY = 60; int maxY = 230; //for x, start at 30 and end at 450 int minX = 10; int maxX = 470; for (int i = 0; i < errorHistory.size() - 1; i++) { int x = minX + (maxX - minX) * i / errorHistory.size(); //graph velocity Brain.Screen.setPenColor(green); Brain.Screen.drawLine(x, minY + (float)errorHistory.at(i) / goal * (maxY - minY), x + (float)(maxX - minX) / errorHistory.size(), minY + (float)errorHistory.at(i + 1) / goal * (maxY - minY)); //graph power //change color based on direction if (powerHistory.at(i) > 0) { Brain.Screen.setPenColor(orange); } else { Brain.Screen.setPenColor(yellow); } Brain.Screen.drawLine(x, maxY - std::abs(powerHistory.at(i)) * (maxY - minY), x + (float)(maxX - minX) / errorHistory.size(), maxY - std::abs(powerHistory.at(i + 1)) * (maxY - minY)); } } void drawRobotPath(std::vector x, std::vector y) { //draws the path of the robot (as discerned from odometry) on the brain of the robot Brain.Screen.clearScreen(); Brain.Screen.setPenWidth(1); Brain.Screen.setPenColor(green); Brain.Screen.drawLine(0, 120, 480, 120); Brain.Screen.drawLine(240, 0, 240, 240); Brain.Screen.setPenColor(white); Brain.Screen.setPenWidth(2); int originX = 240; int originY = 120; float scale = 2; for (int i = 0; i < x.size() - 1; i++) { Brain.Screen.drawLine(x.at(i) * scale + originX, 240 - (y.at(i) * scale + originY), x.at(i + 1) * scale + originX, 240 - (y.at(i + 1) * scale + originY)); } //draw robot as dot Brain.Screen.setPenColor(red); Brain.Screen.drawCircle(x.at(x.size() - 1) * scale + originX, 240 - (y.at(x.size() - 1) * scale + originY), 5); } /*template for a thread/task (task is a higher level abstraction of thread): int myTaskCallback() { while (true) { //do something wait(25, msec); } // A task's callback must return an int, even though the code will never get // here. You must return an int here. Tasks can exit, but this one does not. return 0; } in some other function like main(): task myTask = task(myTaskCallback); */ int updatePosition() { //keep track of position over time std::vector x; std::vector y; while (true) { //odometry, yay! //caclulate the robot's absolute position //first calculate the change since last time float changeLeft = LeftEncoder.position(degrees) - prevLeftEncoder; float changeRight = RightEncoder.position(degrees) - prevRightEncoder; float changeBack = BackEncoder.position(degrees) - prevBackEncoder; prevLeftEncoder = LeftEncoder.position(degrees); prevRightEncoder = RightEncoder.position(degrees); prevBackEncoder = BackEncoder.position(degrees); //convert the changes to inches //degrees * (1 revolution / 360 degrees) * (pi * 2.75" (diameter of wheel) / 1 revolution) = inches //although the actual wheel size differs by a small amount, it was 2.73 for the first half of the second week of summer camp //after that it is off by 1.021836:1 difference (back wheel) //for the right wheel our new ratio is 1.011 float distLeft = (float)changeLeft / 360 * M_PI * 2.75; float distRight = (float)changeRight / 360 * M_PI * 2.75; float distBack = (float)changeBack / 360 * M_PI * 2.75; //calculates the change in angle according to an equation derived in the notebook float changeInAngle = (distLeft- distRight) / (sideWheelRadius * 2); float newAngle = angle + changeInAngle; //now calculate the change in translational offset //x is forward, so a changeX of +2.5 means the robot moved directly forward 2.5 inches //y is sideways, left is positive. Think of a cartesian coordinate system. float changeX = 0; //we need a third tracking wheel for this float changeY = 0; //set to zero initially //we avoid a divide by zero error by splitting the code based on whether the change in angle is zero or not if (changeInAngle == 0) { changeY = distBack; //there was no turning, so the lateral change in position is interepereted simply changeX = distRight; } else { //now you have to account for the fact that going forward while turning changes the position differently changeX = 2 * sin(changeInAngle / 2) * ((distRight / changeInAngle) + sideWheelRadius); changeY = 2 * sin(changeInAngle / 2) * ((distBack / changeInAngle) + backWheelRadius); } //now convert local position change to global position //the local coordinate system is offset from the global one by (angle + newAngle) / 2 //first convert to polar coordinates float radius = sqrt(changeY * changeY + changeX * changeX); float globalAngle = atan2(changeY, changeX) + (angle + newAngle) / 2; //now convert back to local coordinates float changeGlobalX = cos(globalAngle) * radius; float changeGlobalY = sin(globalAngle) * radius; //update global position pos[0] += changeGlobalX; pos[1] += changeGlobalY; angle += changeInAngle; //graph the robot's position if necessary if (drawMode == 3) { x.push_back(pos[0]); y.push_back(pos[1]); drawRobotPath(x, y); } wait(4, msec); } return 0; } int flywheelVelocityControl(){ int prevError = 0; //previous error float motorPower = 0; //between 0 and 1, the proportion of motor power applied (.7 = 70% power float prevMotorPower = 0; //previous motor power, used to limit the slew rate float powerAtZero = 0; //the tbh variable, the best guess of the flywheel power to use std::vector velocityHistory; //keep track of velocity over time std::vector powerHistory; //keep track of motor power over time //this task keeps track of the velocity of the flywheel and manages the motor power input while (true) { //first, get the current velocity of the flywheel. 5:1 gear ratio int speed = Flywheel.velocity(rpm) * 5; int error = flywheelTargetRPM - speed; //now for the tbh (take back half) algorithm //similar to PID but minimizes overshoot motorPower = motorPower + (gain * error); ///keep motor power variable in proper range if (motorPower > 1) motorPower = 1; if (motorPower < 0) motorPower = 0; //control the slew rate (dampen voltage differences), basically don't jerk the motor too much float slewRate = 0.05f; if (motorPower > prevMotorPower + slewRate) { motorPower = prevMotorPower + slewRate; } if (motorPower < prevMotorPower - slewRate) { motorPower = prevMotorPower - slewRate; } //the other key component of the take back half algorithm, the part that takes back half if (error >= 0 != prevError >= 0) { //the graph crossed the target RPM line if (!firstCross) { //the first time you cross the target RPM, slow it down to the voltage estimate to make it stabilize faster firstCross = true; motorPower = motorPowerApprox; } else { //every time after the first time you cross the target RPM, set the voltage to be the average of what it currently is and what is was at the previous cross motorPower = 0.5 * (motorPower + powerAtZero); } powerAtZero = motorPower; } //if the flyhweel is off, take that into account if (!flywheelOn) { motorPower = 0; powerAtZero = 0; firstCross = false; } if (tripleShooting) motorPower = .75;//might have to undo this, helps with consistency in some situations. //now apply motor power, if we are using this control method if (useTBH) Flywheel.spin(forward, 12 * motorPower, volt); //update history of velocity and motor power velocityHistory.push_back(speed); powerHistory.push_back(motorPower * 100); //graph if necessary if (drawMode == 0) { graphFlywheelVelocity(velocityHistory, powerHistory); } //update previous variables prevMotorPower = motorPower; prevError = error; //don't hog CPU wait(20, msec); } return 0; } void driveCode() { //drives the robot around based on controller input, double arcade controls //don't drive if the robot is currently being controlled autonomously if (auton) return; LeftMotors.spin(forward); RightMotors.spin(forward); int forward1 = Controller1.Axis3.value(); int turn = Controller1.Axis1.value(); printController(LeftMotors.velocity(rpm)); //fix drift, or not //if (std::abs(forward) < 7) forward = 0; //if (std::abs(turn) < 7) turn = 0; //calculate proper motor powers int left = forward1 * driveSpeed + turn * turnSpeed; int right = forward1 * driveSpeed - turn * turnSpeed; //set velocity of drive motors LeftMotors.setVelocity(left, percent); RightMotors.setVelocity(right, percent); LeftMotors.spin(forward, left, percent); } //now all of the functions for autonomous / odometry int turnToPoint(float x, float y) { //given an X and Y position on the field, turn to that point using PID //PID constants: float kP = 0.03; float kI = 0.03; float kD = 0.001; //other variables: float error = 0; float motorPower = 0; float integral = 0; float derivative = 0; float prevError = 0; float prevMotorPower = 0; //first, calculate the angle we need to be at float deltaX = x - pos[0]; float deltaY = y - pos[1]; float finalAngle = atan2(deltaY, deltaX); //in radians //also clamp the current angle to [0, 2pi) while (angle >= 2 * M_PI) { angle -= 2 * M_PI; } while (angle < 0) { angle += 2 * M_PI; } while(true) { //calculate error / integral / derivative, of error vs time graph error = finalAngle - angle; integral += error; derivative = error - prevError; //core of the PID loop here, calculate the necessary motor power motorPower = kP * error + kI * integral + kD * derivative; ///keep motor power variable in proper range, 0-1 if (motorPower > 1) motorPower = 1; if (motorPower < 0) motorPower = 0; //control the slew rate (dampen voltage differences), limits harsh acceleration float slewRate = 0.05f; if (motorPower > prevMotorPower + slewRate) { motorPower = prevMotorPower + slewRate; } if (motorPower < prevMotorPower - slewRate) { motorPower = prevMotorPower - slewRate; } //apply motor voltages LeftMotors.spin(forward, 12 * motorPower, volt); RightMotors.spin(reverse, 12 * motorPower, volt); //update final variables prevMotorPower = motorPower; prevError = error; //don't hog CPU wait(20, msec); } return 0; } int drivePID() { //drive straightforward with driveDistance as the distance, in degrees (for now) //forward PID constants: float kP1 = 0.0048;//.003 and 0 for other two float kI1 = 0.00003; float kD1 = 0.013; //turning PID constants: float kP2 = 0.001; float kI2 = 0.00; float kD2 = 0.00; //other variables for forward PID float error1 = 0; float integral1 = 0; float derivative1 = 0; float prevError1 = 0; //other variables for turn PID float error2 = 0; float integral2 = 0; float derivative2 = 0; float prevError2 = 0; //motor power variables float motorPower = 0; float prevMotorPower = 0; //lists std::vector errorHistory; //keep track of error over time std::vector powerHistory; //keep track of motor power over time int time = 0; float currentDist = 0; //the distance the robot is from its starting point RightMotors.setPosition(0, degrees); LeftMotors.setPosition(0, degrees); while(true) { currentDist = (RightMotors.position(degrees) + LeftMotors.position(degrees)) / 2; //calculate error / integral / derivative, of error vs time graph error1 = driveDistance - currentDist; if (std::abs(error1) < 200) { //weigh the integral double when error < 50 if (std::abs(error1) < 50) { integral1 += error1 * 2; } else { integral1 += error1; } } derivative1 = error1 - prevError1; error2 = RightMotors.position(degrees) - RightMotors.position(degrees); integral2 += error2; derivative2 = error2 - prevError2; //core of the PID loop here, calculate the necessary motor power, combine both PID loops motorPower = (kP1 * error1 + kI1 * integral1 + kD1 * derivative1); ///keep motor power variable in proper range, -1 to 1 if (motorPower > 1) motorPower = 1; if (motorPower < -1) motorPower = -1; //control the slew rate (dampen voltage differences), limits harsh acceleration float slewRate = 0.08f; if (motorPower > prevMotorPower + slewRate) { motorPower = prevMotorPower + slewRate; } if (motorPower < prevMotorPower - slewRate) { motorPower = prevMotorPower - slewRate; } //apply motor voltages LeftMotors.spin(forward, 11 * motorPower * speedPID, volt); RightMotors.spin(forward, 11 * motorPower * speedPID, volt); //update final variables prevMotorPower = motorPower; prevError1 = error1; prevError2 = error2; //update histories errorHistory.push_back(error1); powerHistory.push_back(std::abs(motorPower)); time += 20; //break out of the loop if we have reached the target or B is pressed //we have reached the target if the error is less than 5 and the previous error is similar if (Controller1.ButtonB.pressing() || ((std::abs(error1) < 5) && std::abs(error1 - prevError1) < 2)) { break; } //don't hog CPU wait(20, msec); } wait(20, msec); //allow time for status update to draw itself //graph the PID at the end drawMode = 1; graphPID(errorHistory, powerHistory, driveDistance, error1, time); LeftMotors.stop(); RightMotors.stop(); return 0; } int turnPID() { //drive straightforward with driveDistance as the distance, in degrees (for now) //forward PID constants: //zieger-nicholas on 11/14: ku = .07 period = .5 sec float kP1 = 0.034;//.0245;//.0225 and 0 for other two float kI1 = 0.0037;//0.0017; //0.0017 float kD1 = 0.19;//0.06;//0.010; //not bad; 0.017, 0.0042, 0 //not bad v2; .04, 0.0037, 0.23 //other variables for forward PID float error = 0; float integral = 0; float derivative = 0; float prevError = 0; //motor power variables float motorPower = 0; float prevMotorPower = 0; //lists std::vector errorHistory; //keep track of error over time std::vector powerHistory; //keep track of motor power over time int time = 0; float currentDist = 0; //the distance the robot is from its starting point, rotationally float startDist = (Inertial1.rotation(degrees) + Inertial2.rotation(degrees)) / 2; //Inertial1.setHeading(0, degrees); //Inertial2.setHeading(0, degrees); //float degOffset while(true) { //float deg1 = Inertial1.heading(degrees); currentDist = (Inertial1.rotation(degrees) + Inertial2.rotation(degrees)) / -2 + startDist; //printController(Inertial1.rotation(degrees)); //calculate error / integral / derivative, of error vs time graph error = driveDistance - currentDist; if (std::abs(error) < 8) { //weigh the integral double when error < 4 if (std::abs(error) < 3) { integral += error * 2; } else { integral += error; } } else { integral = 0; } derivative = error - prevError; //core of the PID loop here, calculate the necessary motor power, combine both PID loops motorPower = (kP1 * error + kI1 * integral + kD1 * derivative); ///keep motor power variable in proper range, -1 to 1 if (motorPower > 1) motorPower = 1; if (motorPower < -1) motorPower = -1; //control the slew rate (dampen voltage differences), limits harsh acceleration float slewRate = 0.08f; if (motorPower > prevMotorPower + slewRate) { motorPower = prevMotorPower + slewRate; } if (motorPower < prevMotorPower - slewRate) { motorPower = prevMotorPower - slewRate; } //minimum voltage of 11V * .2 /*if (std::abs(slewRate) != .12) { if (std::abs(motorPower) < 0.2) { if (motorPower > 0) { motorPower = 0.2; } else { motorPower = -0.2; } } }*/ //apply motor voltages LeftMotors.spin(forward, 11 * motorPower * -1, volt); RightMotors.spin(forward, 11 * motorPower, volt); //update histories errorHistory.push_back(error); powerHistory.push_back(motorPower); time += 20; //update final variables //printController(error); //break out of the loop if we have reached the target or B is pressed //we have reached the target if the error is less than 5 and the previous error is similar if (Controller1.ButtonB.pressing() || ((std::abs(error) < 0.5) && std::abs(error - prevError) < 0.3)) { break; } prevMotorPower = motorPower; prevError = error; //don't hog CPU wait(20, msec); } wait(20, msec); //allow time for status update to draw itself //graph the PID at the end drawMode = 1; graphPID(errorHistory, powerHistory, driveDistance, error, time); LeftMotors.stop(); RightMotors.stop(); return 0; } void aDrive(float distance) { driveDistance = distance; drivePID(); } void aTurn(float distance) { driveDistance = distance; turnPID(); } void aDriveFor(int speed, int time) { //drive the robot forward (or backward if speed is negative) for a specified amount of milliseconds RightMotors.spin(forward); LeftMotors.spin(forward); RightMotors.setVelocity(speed, percent); LeftMotors.setVelocity(speed, percent); wait(time, msec); LeftMotors.stop(); RightMotors.stop(); } void fireIndexer() { Indexer.spin(forward, 12, volt); wait(130, msec); Indexer.spin(forward, 6, volt); wait(60, msec); Indexer.spin(reverse, 6, volt); wait(100, msec); Indexer.stop(); } //below code copied from jpearman on vexforum int screen_origin_x = 150; int screen_origin_y = 20; int screen_width = 316; int screen_height = 212; // function to draw a single object void drawObject( vision::object &obj, vex::color c ) { int labelOffset = 0; Brain.Screen.setPenColor( vex::color::yellow ); Brain.Screen.drawRectangle( screen_origin_x + obj.originX, screen_origin_y + obj.originY, obj.width, obj.height, c ); Brain.Screen.setFont( vex::fontType::mono12 ); if( obj.originX > 280 ) labelOffset = -40; if( obj.originY > 10 ) Brain.Screen.printAt( screen_origin_x + obj.originX + labelOffset, screen_origin_y + obj.originY-3, "Sig %o", obj.id ); else Brain.Screen.printAt( screen_origin_x + obj.originX + labelOffset, screen_origin_y + obj.originY+10, "Sig %o", obj.id ); } // function to draw all objects found void drawObjects( vision &v, vex::color c, bool clearScreen ) { if( clearScreen ) { Brain.Screen.setPenColor( vex::color::black ); Brain.Screen.drawRectangle( screen_origin_x, screen_origin_y, screen_width, screen_height, vex::color::black ); } for(int i=0;i maxArea && area > 400) { maxArea = area; maxX = VisionSensor.largestObject.originX + (VisionSensor.largestObject.width / 2); } } if (visionTrackBlue) { VisionSensor.takeSnapshot( VisionSensor__BLUE_GOAL ); int area = VisionSensor.largestObject.width * VisionSensor.largestObject.height; if (area > maxArea && area > 400) { maxArea = area; maxX = VisionSensor.largestObject.originX + (VisionSensor.largestObject.width / 2); } } wait(20, msec); } if (maxX == -1) { //dont do anything if no goal is detected x = center; printControllerSetup(); Controller1.Screen.print("No goal found"); } else { x = maxX; } float value = x / 316.0 * 60; //angle, in degrees, that we are at. 30 degrees is dead center finalValue = (value - 30) * -7.55; //degree-to-PID units conversion //only turn if we are off by a good bit (over 1 degree) if (std::abs(finalValue) > 7) { aTurn(finalValue); } } while (std::abs(finalValue) > 7); return 0; } void flipRoller() { //flips a roller, just like that Intake.spin(forward, 11, volt); while(Optical.hue() > 50 || !Optical.isNearObject()) { RightMotors.spin(forward, 2, volt); LeftMotors.spin(forward, 2, volt); wait(20, msec); } Intake.stop(); } void autonomousProgram(void) { auton = true; //wait until inertial is calibrated while (Inertial1.isCalibrating()) { wait(30, msec); printControllerSetup(); Controller1.Screen.print("Calibrating Inertial"); } int timerValue = Brain.Timer.value(); //run the autonomous program based on the autonType variable if (autonType == 0) { //testing one aTurn(flywheelTargetRPM); } else if (autonType == 1) { //standard autonomous, left side roller + shoot 5 discs flywheelOn = true; flywheelTargetRPM = 2200; //45 motorPowerApprox = 0.73; gain = 0.000123; Intake.spin(forward, 11, volt); aDriveFor(20, 300); Intake.stop(); aDrive(-100); //aTurn(-2); //;UNDO drawMode = 0; wait(1700, msec); ///UNDOO fireIndexer(); wait(1100, msec); fireIndexer(); wait(300, msec); aDrive(-100); motorPowerApprox = 0.61; flywheelTargetRPM = 2160; gain = 0.000093; aTurn(119); Intake.spin(reverse, 12, volt); aDrive(750); speedPID = 1; aDrive(300); aDrive(300); speedPID = 1; //aDriveFor(50, 2100); //wait(200, msec); aTurn(-89); drawMode = 0; //Intake.spin(forward, 12, volt); wait(100, msec); fireIndexer(); Intake.spin(reverse, 12, volt); wait(350, msec); fireIndexer(); tripleShooting = true; wait(400, msec); Intake.stop(); fireIndexer(); wait(400, msec); tripleShooting = false; flywheelOn = false; flywheelTargetRPM = 1800; gain = defaultGain; } else if (autonType == 2) { flywheelOn = true; flywheelTargetRPM = 2120; Intake.spin(reverse, 11, volt); aDrive(700); aTurn(150); Intake.stop(); drawMode = 0; wait(800, msec); fireIndexer(); wait(200, msec); fireIndexer(); wait(100, msec); fireIndexer(); wait(200, msec); flywheelTargetRPM = 2060; aTurn(-96); Intake.spin(reverse, 11, volt); speedPID = .8; aDrive(850); speedPID = 1; wait(100, msec); //Intake.spin(forward, 6, volt); aTurn(78); Intake.spin(reverse, 11, volt); fireIndexer(); wait(300, msec); Intake.stop(); fireIndexer(); wait(200, msec); aTurn(103); aDrive(1600); RightMotors.spin(forward); LeftMotors.spin(forward); RightMotors.setVelocity(20, percent); LeftMotors.setVelocity(100, percent); wait(600, msec); RightMotors.stop(); LeftMotors.stop(); Intake.spin(forward, 11, volt); wait(100, msec); aDriveFor(20, 400); Intake.stop(); aDriveFor(-90, 100); /*aTurn(-160); drawMode = 0; wait(1700, msec); fireIndexer(); wait(200, msec); fireIndexer(); aDrive(-100); aTurn(-460); flywheelTargetRPM = 2100; aDrive(-620); aTurn(650); Intake.spin(forward, 11, volt); aDriveFor(20, 800); Intake.stop(); aDrive(-130); aTurn(-930); Intake.spin(reverse, 11, volt); speedPID = 0.6; aDrive(1800); speedPID = 1; //Intake.spin(forward, 5, volt); aTurn(610); wait(200, msec); Intake.spin(reverse, 11, volt); fireIndexer(); wait(400, msec); Intake.stop();*/ flywheelOn = false; flywheelTargetRPM = 1800; } else if (autonType == 3) { //go from roller to match load station aDrive(-400); aTurn(-300); aDrive(-700); aTurn(160); LeftMotors.spin(forward); RightMotors.spin(forward); for (int i = 0; i < 25; i++) { int forward = -50; int turn = (25 - (i * 1.0)) * -1; //calculate proper motor powers int left = forward * driveSpeed + turn * turnSpeed; int right = forward * driveSpeed - turn * turnSpeed; //set velocity of drive motors LeftMotors.setVelocity(left, percent); RightMotors.setVelocity(right, percent); wait(40, msec); } } else if (autonType == 4) { alignToGoal(); } else if (autonType == 5) { //programming skills flywheelOn = true; wait(2000, msec); opticalMode = true; flywheelTargetRPM = 1800; Intake.spin(forward); Intake.setVelocity(100, percent); wait(12000, msec); Intake.stop(); opticalMode = false; //flywheelOn = false; aTurn(-92); aDrive(550); aTurn(90); Intake.spin(reverse); aDrive(300); wait(500, msec); aDrive(200); wait(500, msec); aDrive(200); aDrive(-800); aTurn(-25); Intake.stop(); fireIndexer(); wait(600, msec); fireIndexer(); wait(600, msec); fireIndexer(); wait(300, msec); aTurn(26); Intake.spin(reverse); aDrive(1000); wait(500, msec); aDrive(200); wait(500, msec); aDrive(200); wait(500, msec); aDrive(200); aTurn(-90); aDrive(600); aTurn(-90); Intake.stop(); aDriveFor(-50, 1800); aDrive(400); aTurn(-90); aDrive(-500); fireIndexer(); wait(600, msec); fireIndexer(); wait(600, msec); fireIndexer(); wait(300, msec); aDrive(1500); aTurn(-45); Wings.set(true); wait(2000, msec); aDrive(-100); //aDrive(300); /* aTurn(45); aDrive(300); Wings.set(true); wait(2000, msec); aDrive(-100);*/ flywheelOn = false; flywheelTargetRPM = 1800; } else if (autonType == 6) { flywheelOn = true; flywheelTargetRPM = 2100; gain = 0.000093; wait(3000, msec); drawMode = 0; Intake.spin(forward, 12, volt); wait(100, msec); fireIndexer(); Intake.spin(reverse, 12, volt); wait(350, msec); fireIndexer(); tripleShooting = true; wait(400, msec); Intake.stop(); fireIndexer(); wait(400, msec); //the above code is very precise tripleShooting = false; flywheelOn = false; } else if (autonType == 7) { //flip a roller flipRoller(); Intake.stop(); //flywheelOn = false; } printController(Brain.Timer.value() - timerValue);//print time it took auton = false; } int opticalModeLoop() { //shoot discs if the optical sensor detects something while (true) { //check if it is optical sensor mode wait(25, msec); if (!opticalMode) continue; //printControllerSetup(); //Controller1.Screen.print(Optical.isNearObject()); //disc detected when reflectivity is greater than 90 if (LineTracker.reflectivity() > 90) { wait(300, msec); //fire one disc Indexer.spin(forward, 12, volt); wait(130, msec); Indexer.spin(forward, 6, volt); wait(60, msec); Indexer.spin(reverse, 6, volt); wait(70, msec); Indexer.stop(); wait(100, msec); } } return 0; } void buttonL1Pressed() { if (Controller1.ButtonB.pressing()){ visionTrackRed = true; visionTrackBlue = false; printControllerSetup(); Controller1.Screen.print("Vision Track: RED"); } else { Intake.spin(forward, 11, volt); } } void buttonL2Pressed() { if (Controller1.ButtonB.pressing()){ visionTrackRed = false; visionTrackBlue = true; printControllerSetup(); Controller1.Screen.print("Vision Track: BLUE"); } else { Intake.spin(reverse, 11, volt); } } void buttonL1Released() { Intake.stop(); } void buttonL2Released() { Intake.stop(); } void buttonR1Pressed() { //retract extension mechanism Wings.set(false); } void buttonR2Pressed() { //expand extension mechanism, if button B is pressed if (Controller1.ButtonB.pressing()) { Wings.set(true); } } void buttonUpPressed() { //increase the RPM of the flywheel when the up button is pressed if (Controller1.ButtonB.pressing()) { //fine control if another button is held down flywheelTargetRPM += 10; } else { flywheelTargetRPM += 100; } printController(flywheelTargetRPM); } void buttonDownPressed() { //decrease the RPM of the flywheel when the down button is pressed if (Controller1.ButtonB.pressing()) { //fine control if another button is held down flywheelTargetRPM -= 10; } else { flywheelTargetRPM -= 100; } printController(flywheelTargetRPM); } void buttonLeftPressed() { //align to goal first lol auton = true; if (visionAlign) { alignToGoal(); } else { //display the number int x = 0; int center = 158;// the goal should be at x=100 when lined up perfectly with the robot //look at the leftmost instance of the goal int maxArea = 0; int maxX = -1; for (int k = 0; k < 5; k++) { if (visionTrackRed) { VisionSensor.takeSnapshot( VisionSensor__RED_GOAL ); //if this is the new highest area, then update the variable int area = VisionSensor.largestObject.width * VisionSensor.largestObject.height; if (area > maxArea && area > 400) { maxArea = area; maxX = VisionSensor.largestObject.originX + (VisionSensor.largestObject.width / 2); } } if (visionTrackBlue) { VisionSensor.takeSnapshot( VisionSensor__BLUE_GOAL ); int area = VisionSensor.largestObject.width * VisionSensor.largestObject.height; if (area > maxArea && area > 400) { maxArea = area; maxX = VisionSensor.largestObject.originX + (VisionSensor.largestObject.width / 2); } } wait(20, msec); } if (maxX == -1) { //dont do anything if no goal is detected x = center; } else { x = maxX; } printController((x / 316.0 * 60) - 30); } auton = false; //automatically fire all three disc Indexer.spin(forward, 11, volt); wait(200, msec); Indexer.spin(reverse, 11, volt); wait(120, msec); Indexer.spin(reverse, 3, volt); tripleShooting = true; wait(50, msec); Indexer.spin(forward, 11, volt); wait(200, msec); Indexer.spin(reverse, 11, volt); wait(120, msec); Indexer.spin(reverse, 3, volt); wait(50, msec); Indexer.spin(forward, 11, volt); wait(200, msec); Indexer.spin(reverse, 11, volt); wait(120, msec); Indexer.stop(); tripleShooting = false; } void buttonRightPressed() { //if b is pressed, toggle optical sensor mode if (Controller1.ButtonB.pressing()) { opticalMode = !opticalMode; //display a note on the controller, and also spin the intake in the right way if (opticalMode) { Intake.spin(forward); Intake.setVelocity(100, percent); printControllerSetup(); Controller1.Screen.print("Autoshoot mode enabled"); //gain = 0.000103; flywheelTargetRPM = 1800; } else { Intake.stop(); printControllerSetup(); Controller1.Screen.print("Autoshoot mode disabled"); gain = defaultGain; //was 0.00013 before flywheelTargetRPM = 1800; } } else { //fire one disc fireIndexer(); } } void buttonXPressed() { //turn on or off the flywheel //count the time it takes for rpm to reach 0 /* if (!flywheelOn) { int fTimer = 0; while (Flywheel.velocity(rpm) != 0){ wait(20, msec); fTimer += 20; } printController(fTimer); }*/ if (Controller1.ButtonB.pressing()) { //change the drawing mode and let the driver know if (tempDrawMode < 9) { drawMode = tempDrawMode + 1; } else { drawMode = tempDrawMode - 9; } if (drawMode > 3) drawMode = 0; tempDrawMode = drawMode + 10;//let the release Button B function know that we changed the drawing mode //printController(drawMode); printControllerSetup(); if (drawMode == 0) { Controller1.Screen.print("Draw: Flywheel graph"); } else if (drawMode == 1) { Controller1.Screen.print("Draw: PID graph"); } else if (drawMode == 2) { Controller1.Screen.print("Draw: Vision sensor"); } } else { flywheelOn = !flywheelOn; //backup: velocity control based on internal motor PID's (it's bad) if (useTBH == false) { if (flywheelOn) { Flywheel.setVelocity(100, percent); Flywheel.spin(forward); } else { Flywheel.setVelocity(0, percent); } } } } void buttonXReleased() { } void buttonAPressed() { //reset odometry; if B is held down then display odometry constants instead if (!Controller1.ButtonB.pressing()) { /* Controller1.Screen.clearScreen(); Controller1.Screen.setCursor(1, 1); Controller1.Screen.print(pos[0]); Controller1.Screen.newLine(); Controller1.Screen.print(pos[1]); Controller1.Screen.newLine(); Controller1.Screen.print(angle * 180 / M_PI); */ } else { pos[0] = 0; pos[1] = 0; angle = 0; } } void buttonBPressed() { //prints out a bunch of useful information on the brain screen--a status check Brain.Screen.clearScreen(); Brain.Screen.setCursor(1, 1); Brain.Screen.print("Battery voltage: "); Brain.Screen.print(Brain.Battery.voltage()); Brain.Screen.newLine(); Brain.Screen.print("Battery current: "); Brain.Screen.print(Brain.Battery.current()); Brain.Screen.newLine(); Brain.Screen.print("Left Motors temp: "); Brain.Screen.print(LeftMotors.temperature(percent)); Brain.Screen.newLine(); Brain.Screen.print("Right motors temp: "); Brain.Screen.print(RightMotors.temperature(percent)); Brain.Screen.newLine(); Brain.Screen.print("Flywheel temp: "); Brain.Screen.print(Flywheel.temperature(percent)); Brain.Screen.newLine(); Brain.Screen.print("Intake temp: "); Brain.Screen.print(Intake.temperature(percent)); Brain.Screen.newLine(); Brain.Screen.print("Indexer temp: "); Brain.Screen.print(Indexer.temperature(percent)); Brain.Screen.newLine(); tempDrawMode = drawMode; drawMode = 3; } void buttonBReleased() { //we changed the drawing mode while we were holding down B, so change it to the new one if (tempDrawMode < 9) { drawMode = tempDrawMode; } } void buttonYPressed() { //change up what is drawn on the brain screen. //drawPath = !drawPath; //drawFlywheelGraph = !drawFlywheelGraph; //start autonomous if A is held down while pressing Y if (Controller1.ButtonA.pressing()) { autonomousProgram(); } else if (Controller1.ButtonB.pressing()) { visionAlign = !visionAlign; printControllerSetup(); if (visionAlign) { Controller1.Screen.print("Vision align enabled"); } else { Controller1.Screen.print("Vision align disabled"); } } else { autonType++; if (autonType > 7) autonType = 0; printControllerSetup(); Controller1.Screen.print("Auton type: "); Controller1.Screen.print(autonType); } } void checkOverheating() { //check for overheating in any of the motors if (LeftMotors.temperature(percent) > 50 || RightMotors.temperature(percent) > 50 || Flywheel.temperature(percent) > 50 || Intake.temperature(percent) > 50 || Indexer.temperature(percent) > 50) { if (overHeatingTimer == 0) { Controller1.rumble(rumbleLong); printControllerSetup(); Controller1.Screen.print("Overheating Warning"); overHeatingTimer++; } else { overHeatingTimer++; if (overHeatingTimer > 750) overHeatingTimer = 0; } } if (Controller1.ButtonR2.pressing() && !Controller1.ButtonB.pressing()) { printController(Intake.velocity(rpm)); wait(500, msec); } } void init() { //initialize settings, variables, and callback functions Flywheel.setStopping(coast); Intake.setStopping(coast); Indexer.setStopping(coast); LeftMotors.setStopping(coast); RightMotors.setStopping(coast); gain = defaultGain; //callbacks for other driver controls //intake Controller1.ButtonL1.pressed(buttonL1Pressed); Controller1.ButtonL2.pressed(buttonL2Pressed); Controller1.ButtonL1.released(buttonL1Released); Controller1.ButtonL2.released(buttonL2Released); //expansion Controller1.ButtonR1.pressed(buttonR1Pressed); Controller1.ButtonR2.pressed(buttonR2Pressed); //velocity control Controller1.ButtonUp.pressed(buttonUpPressed); Controller1.ButtonDown.pressed(buttonDownPressed); //indexer Controller1.ButtonLeft.pressed(buttonLeftPressed); Controller1.ButtonRight.pressed(buttonRightPressed); //other functions Controller1.ButtonX.pressed(buttonXPressed); Controller1.ButtonX.released(buttonXReleased); Controller1.ButtonA.pressed(buttonAPressed); Controller1.ButtonB.pressed(buttonBPressed); Controller1.ButtonB.released(buttonBReleased); Controller1.ButtonY.pressed(buttonYPressed); //background tasks (very important) //task myTask = task(updatePosition); task myTask1 = task(flywheelVelocityControl); task myTask2 = task(opticalModeLoop); } void pre_auton(void) { init(); Inertial1.calibrate(); Inertial2.calibrate(); } void usercontrol(void) { auton = false; flywheelTargetRPM = 1800; gain = defaultGain; tripleShooting = false; while (1) { driveCode(); //testing with encoders /* Controller1.Screen.clearScreen(); Controller1.Screen.setCursor(1, 1); Controller1.Screen.print(RightEncoder.position(degrees)); Controller1.Screen.newLine(); Controller1.Screen.print(LeftEncoder.position(degrees)); Controller1.Screen.newLine(); Controller1.Screen.print(BackEncoder.position(degrees)); */ //copied from jpearman // Draw an area representing the vision sensor field of view if (drawMode == 2) { Brain.Screen.clearScreen( vex::color::black ); Brain.Screen.setPenColor( vex::color::green ); Brain.Screen.drawRectangle( screen_origin_x-1, screen_origin_y-1, screen_width+2, screen_height+2 ); // request any objects with signature 1 int numberObjects = VisionSensor.takeSnapshot(VisionSensor__RED_GOAL); Brain.Screen.setPenColor( vex::color::white ); Brain.Screen.setFont( mono20 ); Brain.Screen.setCursor( 2, 2 ); Brain.Screen.print( "Sig 1 %2d", (int)numberObjects ); // draw any objects found drawObjects( VisionSensor, vex::color::red, true ); numberObjects = VisionSensor.takeSnapshot(VisionSensor__BLUE_GOAL); // draw any objects found drawObjects( VisionSensor, vex::color::blue, false ); wait(180, msec); } wait(20, msec); } } int main() { // Initializing Robot Configuration. DO NOT REMOVE! vexcodeInit(); // Set up callbacks for autonomous and driver control periods. Competition.autonomous(autonomousProgram); Competition.drivercontrol(usercontrol); // Run the pre-autonomous function, basically initialize pre_auton(); // Prevent main from exiting with an infinite loop. while (true) { checkOverheating(); //printController(Optical.hue()); wait(20, msec); } } Full Over Under Code //necessary stuff #include "vex.h" #include #include #include #include using namespace vex; competition Competition; //global variables bool auton = false; //whether or not the robot is being controlled autonomously float driveSpeed = 1.0f; //driving (forward and backward) speed of the robot float turnSpeed = .6f; //turning speed of the robot int drawMode = 3; //what to draw on the brain screen? 0: flywheel 1: PID 2: vision sensor 3: status update 4: odom int tempDrawMode = 0; //store the previous draw mode temporarily int overHeatingTimer = 0; //keeps track of how often to display an overheating warning int autonType = 2; //the type of autonomous to use float driveDistance = 0; //drive distance for drive PID float speedPID = 1; // the speed to run the motors at in PID loops, range is 0-1 bool kickerOn = false; //true or false, whether or not the kicker is on right now bool intakeOn = false; //true or false, whether or not the kicker is on right now bool wingsActive = false; //true or false, whether or not the wings are active bool elevationActive = false; //true or false, whether or not the elevation mechanism is active bool scraperActive = false; //true or false, whether or not the scraper is active bool exitPID = false; //true or false, whether or not to exit a PID loop bool curveDrive = true; //true or false, whether or not the curve drive is active task autonTask; //stores the autonomous task //helper functions void printController(float i) { //prints a number to the controller console (very handy for debugging) Controller1.Screen.clearLine(3); Controller1.Screen.setCursor(3, 1); Controller1.Screen.print(i); } void printControllerSetup() { //sets up the controller to be printed on Controller1.Screen.clearLine(3); Controller1.Screen.setCursor(3, 1); } //graphing data, used for PID tuning void graphPID(std::vector errorHistory, std::vector powerHistory, int goal, float error, int time) { //goal is the PID goal //error history is a list of all of the errors //powerHistory is -1 to 1 of the power applied //setup: clear screen and draw the target line Brain.Screen.clearScreen(); Brain.Screen.setPenWidth(2); Brain.Screen.setPenColor(white); Brain.Screen.drawLine(0, 60, 480, 60); Brain.Screen.setPenWidth(1); Brain.Screen.setPenColor(green); //also display amps Brain.Screen.setCursor(1, 1); Brain.Screen.clearLine(1); Brain.Screen.print(" Final Error: "); Brain.Screen.print(error); Brain.Screen.print(" Time: "); Brain.Screen.print(time); //y positions //bottom (0) is 215 //top (100) is 60 //above (110) (overshoot) is <60 int minY = 60; int maxY = 230; //for x, start at 30 and end at 450 int minX = 10; int maxX = 470; for (int i = 0; i < errorHistory.size() - 1; i++) { int x = minX + (maxX - minX) * i / errorHistory.size(); //graph velocity Brain.Screen.setPenColor(green); Brain.Screen.drawLine(x, minY + (float)errorHistory.at(i) / goal * (maxY - minY), x + (float)(maxX - minX) / errorHistory.size(), minY + (float)errorHistory.at(i + 1) / goal * (maxY - minY)); //graph power //change color based on direction if (powerHistory.at(i) > 0) { Brain.Screen.setPenColor(orange); } else { Brain.Screen.setPenColor(yellow); } Brain.Screen.drawLine(x, maxY - std::abs(powerHistory.at(i)) * (maxY - minY), x + (float)(maxX - minX) / errorHistory.size(), maxY - std::abs(powerHistory.at(i + 1)) * (maxY - minY)); } } void drawRobotPath(std::vector x, std::vector y) { //draws the path of the robot (as discerned from odometry) on the brain of the robot Brain.Screen.clearScreen(); Brain.Screen.setPenWidth(1); Brain.Screen.setPenColor(green); Brain.Screen.drawLine(0, 120, 480, 120); Brain.Screen.drawLine(240, 0, 240, 240); Brain.Screen.setPenColor(white); Brain.Screen.setPenWidth(2); int originX = 240; int originY = 120; float scale = 2; for (int i = 0; i < x.size() - 1; i++) { Brain.Screen.drawLine(x.at(i) * scale + originX, 240 - (y.at(i) * scale + originY), x.at(i + 1) * scale + originX, 240 - (y.at(i + 1) * scale + originY)); } //draw robot as dot Brain.Screen.setPenColor(red); Brain.Screen.drawCircle(x.at(x.size() - 1) * scale + originX, 240 - (y.at(x.size() - 1) * scale + originY), 5); } /*template for a thread/task (task is a higher level abstraction of thread): int myTaskCallback() { while (true) { //do something wait(25, msec); } // A task's callback must return an int, even though the code will never get // here. You must return an int here. Tasks can exit, but this one does not. return 0; } in some other function like main(): task myTask = task(myTaskCallback); */ void driveCode() { //drives the robot around based on controller input, double arcade controls //don't drive if the robot is currently being controlled autonomously if (auton) return; Left1.spin(forward); Left2.spin(forward); Left3.spin(forward); Right1.spin(forward); Right2.spin(forward); Right3.spin(forward); int forward1 = Controller1.Axis3.value(); int turn = Controller1.Axis1.value(); //fix drift if (std::abs(forward1) < 7) forward1 = 0; if (std::abs(turn) < 7) turn = 0; //calculate proper motor powers int left; int right; int curveTime = 0; if (curveDrive) { //curvature drive, yay //adjust the straight variable to be non-linear /* if (turn < 10 && turn > -10) { turn = 0; //fix drift } else if (turn < 60 && turn > -60) { turn = (turn / 2) + 10; //fine control for small movements } else { turn = (turn * 3 / 2) - 50; //full power at higher throttles }*/ //adjust the turn variable based on the straight one if (forward1 > 50) { turn *= (((forward1 - 50) / 50) + 1); } else if (forward1 < -50) { turn *= (((-50 - forward1) / 50) + 1); } //Inverse Inertia accumulator--slow down fast turns after 200 ms if (turn < 50 && turn > -50) { curveTime = 0; } if (curveTime > 200) { turn *= 0.6; } //slow down turn: turn *= 0.7; curveTime += 20; } left = forward1 * driveSpeed + turn * turnSpeed; right = forward1 * driveSpeed - turn * turnSpeed; //set velocity of drive motors Left1.setVelocity(left, percent); Left2.setVelocity(left, percent); Left3.setVelocity(left, percent); Right1.setVelocity(right, percent); Right2.setVelocity(right, percent); Right3.setVelocity(right, percent); } int drivePID() { //drive straightforward with driveDistance as the distance, in degrees (for now) //forward PID constants: float kP1 = 0.0016;//.003 and 0 for other two float kI1 = 0.0001; float kD1 = 0.012; //0.0027, 0.0001, and 0.015 with 0.08 slew rate was Brighton values //turning PID constants: float kP2 = 0.02; float kI2 = 0.00; float kD2 = 0.00; //other variables for forward PID float error1 = 0; float integral1 = 0; float derivative1 = 0; float prevError1 = 0; //other variables for turn PID float error2 = 0; float integral2 = 0; float derivative2 = 0; float prevError2 = 0; //motor power variables float motorPower = 0; float prevMotorPower = 0; float headingPower = 0; //lists std::vector errorHistory; //keep track of error over time std::vector powerHistory; //keep track of motor power over time int time1 = 0; float currentDist = 0; //the distance the robot is from its starting point float startDist = Inertial.rotation(degrees); Right1.setPosition(0, degrees); Right2.setPosition(0, degrees); Right3.setPosition(0, degrees); Left1.setPosition(0, degrees); Left2.setPosition(0, degrees); Left3.setPosition(0, degrees); while(true) { currentDist = (Right1.position(degrees) + Left1.position(degrees) + Right2.position(degrees) + Left2.position(degrees) + Right3.position(degrees) + Left3.position(degrees)) / 6; //calculate error / integral / derivative, of error vs time graph error1 = driveDistance - currentDist; if (std::abs(error1) < 200) { //weigh the integral double when error < 50 if (std::abs(error1) < 50) { integral1 += error1 * 2; } else { integral1 += error1; } } derivative1 = error1 - prevError1; //heading correction error2 = Inertial.rotation(degrees) - startDist; if (std::abs(error1) < 600) error2 = 0; integral2 += error2; derivative2 = error2 - prevError2; //core of the PID loop here, calculate the necessary motor power, combine both PID loops motorPower = (kP1 * error1 + kI1 * integral1 + kD1 * derivative1); headingPower = kP2 * error2; ///keep motor power variable in proper range, -1 to 1 if (motorPower > 1) motorPower = 1; if (motorPower < -1) motorPower = -1; //control the slew rate (dampen voltage differences), limits harsh acceleration float slewRate = 0.05f; if (motorPower > prevMotorPower + slewRate) motorPower = prevMotorPower + slewRate; if (motorPower < prevMotorPower - slewRate) motorPower = prevMotorPower - slewRate; //account for heading correction P loop float leftMotorPower = motorPower - headingPower; float rightMotorPower = motorPower + headingPower; if (leftMotorPower > 1) leftMotorPower = 1; if (leftMotorPower < -1) leftMotorPower = -1; if (rightMotorPower > 1) rightMotorPower = 1; if (rightMotorPower < -1) rightMotorPower = -1; //apply motor voltages Left1.spin(forward, 11 * leftMotorPower * speedPID, volt); Left2.spin(forward, 11 * leftMotorPower * speedPID, volt); Left3.spin(forward, 11 * leftMotorPower * speedPID, volt); Right1.spin(forward, 11 * rightMotorPower * speedPID, volt); Right2.spin(forward, 11 * rightMotorPower * speedPID, volt); Right3.spin(forward, 11 * rightMotorPower * speedPID, volt); //update final variables prevMotorPower = motorPower; prevError1 = error1; prevError2 = error2; //update histories errorHistory.push_back(error1); powerHistory.push_back(std::abs(motorPower)); time1 += 20; //break out of the loop if we have reached the target or B is pressed //we have reached the target if the error is less than 5 and the previous error is similar if (Controller1.ButtonB.pressing() || exitPID || ((std::abs(error1) < 8) && std::abs(error1 - prevError1) < 2)) { break; } graphPID(errorHistory, powerHistory, driveDistance, error1, time1); //don't hog CPU wait(20, msec); } wait(20, msec); //allow time for status update to draw itself //graph the PID at the end drawMode = 1; graphPID(errorHistory, powerHistory, driveDistance, error1, time1); Left1.stop(); Left2.stop(); Left3.stop(); Right1.stop(); Right2.stop(); Right3.stop(); return 0; } int turnPID(bool absolute) { //drive straightforward with driveDistance as the distance, in degrees (for now) //forward PID constants: //zieger-nicholas on 11/14: ku = .07 period = .5 sec float kP1 = 0.018;//.0245;//.0225 and 0 for other two float kI1 = 0.0034;//0.0017; //0.0017 //0.0034 float kD1 = 0.12;//0.06;//0.010; //not bad; 0.024, 0.0034, .15 (1/4/23) //other variables for forward PID float error = 0; float integral = 0; float derivative = 0; float prevError = 0; //motor power variables float motorPower = 0; float prevMotorPower = 0; //lists std::vector errorHistory; //keep track of error over time std::vector powerHistory; //keep track of motor power over time int time = 0; float currentDist = 0; //the distance the robot is from its starting point, rotationally float startDist = Inertial.rotation(degrees); //Inertial1.setHeading(0, degrees); //Inertial2.setHeading(0, degrees); //float degOffset while(true) { //float deg1 = Inertial1.heading(degrees); currentDist = Inertial.rotation(degrees) / -1 + startDist; //Inertial2 is much more accurate than inertial1 (10 spins, 23 degress off vs 5 degrees off) //printController(Inertial1.rotation(degrees)); //calculate error / integral / derivative, of error vs time graph error = driveDistance - currentDist; if (absolute) error = driveDistance + Inertial.rotation(degrees); if (std::abs(error) < 10) { //weigh the integral double when error < 4 if (std::abs(error) < 4) { integral += error * 2; } else { integral += error; } } else { integral = 0; } if (error > 0 != prevError > 0) integral = 0;//reset integral value if you just crossed the target line derivative = error - prevError; //core of the PID loop here, calculate the necessary motor power, combine both PID loops motorPower = (kP1 * error + kI1 * integral + kD1 * derivative); ///keep motor power variable in proper range, -1 to 1 if (motorPower > 1) motorPower = 1; if (motorPower < -1) motorPower = -1; //control the slew rate (dampen voltage differences), limits harsh acceleration float slewRate = 0.08; if (motorPower > prevMotorPower + slewRate) { motorPower = prevMotorPower + slewRate; } if (motorPower < prevMotorPower - slewRate) { motorPower = prevMotorPower - slewRate; } //minimum voltage of 11V * .2 /*if (std::abs(slewRate) != .12) { if (std::abs(motorPower) < 0.2) { if (motorPower > 0) { motorPower = 0.2; } else { motorPower = -0.2; } } }*/ //apply motor voltages Left1.spin(forward, 11 * motorPower * -1, volt); Left2.spin(forward, 11 * motorPower * -1, volt); Left3.spin(forward, 11 * motorPower * -1, volt); Right1.spin(forward, 11 * motorPower, volt); Right2.spin(forward, 11 * motorPower, volt); Right3.spin(forward, 11 * motorPower, volt); //update histories errorHistory.push_back(error); powerHistory.push_back(motorPower); time += 20; //update final variables //printController(error); //break out of the loop if we have reached the target or B is pressed //we have reached the target if the error is less than 5 and the previous error is similar if (absolute) { if (Controller1.ButtonB.pressing() || exitPID || ((std::abs(error) < 0.4) && std::abs(error - prevError) < 1)) { break; } } else { if (Controller1.ButtonB.pressing() || exitPID || ((std::abs(error) < 0.5) && std::abs(error - prevError) < 2)) { break; } } prevMotorPower = motorPower; prevError = error; graphPID(errorHistory, powerHistory, driveDistance, error, time); //don't hog CPU wait(20, msec); } wait(20, msec); //allow time for status update to draw itself //graph the PID at the end drawMode = 1; graphPID(errorHistory, powerHistory, driveDistance, error, time); Left1.stop(); Left2.stop(); Left3.stop(); Right1.stop(); Right2.stop(); Right3.stop(); return 0; } void aDrive(float distance) { driveDistance = distance; drivePID(); } void aTurn(float distance) { driveDistance = distance; turnPID(false); } void aDriveFor(int speed, int time) { //drive the robot forward (or backward if speed is negative) for a specified amount of milliseconds Left1.spin(forward); Left2.spin(forward); Left3.spin(forward); Right1.spin(forward); Right2.spin(forward); Right3.spin(forward); Left1.setVelocity(speed, percent); Left2.setVelocity(speed, percent); Left3.setVelocity(speed, percent); Right1.setVelocity(speed, percent); Right2.setVelocity(speed, percent); Right3.setVelocity(speed, percent); wait(time, msec); Left1.stop(); Left2.stop(); Left3.stop(); Right1.stop(); Right2.stop(); Right3.stop(); } //below code copied from jpearman on vexforum int screen_origin_x = 150; int screen_origin_y = 20; int screen_width = 316; int screen_height = 212; // function to draw a single object void drawObject( vision::object &obj, vex::color c ) { int labelOffset = 0; Brain.Screen.setPenColor( vex::color::yellow ); Brain.Screen.drawRectangle( screen_origin_x + obj.originX, screen_origin_y + obj.originY, obj.width, obj.height, c ); Brain.Screen.setFont( vex::fontType::mono12 ); if( obj.originX > 280 ) labelOffset = -40; if( obj.originY > 10 ) Brain.Screen.printAt( screen_origin_x + obj.originX + labelOffset, screen_origin_y + obj.originY-3, "Sig %o", obj.id ); else Brain.Screen.printAt( screen_origin_x + obj.originX + labelOffset, screen_origin_y + obj.originY+10, "Sig %o", obj.id ); } // function to draw all objects found void drawObjects( vision &v, vex::color c, bool clearScreen ) { if( clearScreen ) { Brain.Screen.setPenColor( vex::color::black ); Brain.Screen.drawRectangle( screen_origin_x, screen_origin_y, screen_width, screen_height, vex::color::black ); } for(int i=0;i 7) autonType = 0; printControllerSetup(); Controller1.Screen.print("Auton type: "); Controller1.Screen.print(autonType); } } void buttonXPressed() { //turn on or off the kicker kickerOn = !kickerOn; if (kickerOn) { KickerLED.on(); } else { KickerLED.off(); Kicker.stop(); } } void buttonR2Pressed() { wingsActive = !wingsActive; if (wingsActive) { Wings1.set(true); Wings2.set(true); } else { Wings1.set(false); Wings2.set(false); } } void buttonL1Pressed() { Intake.spin(forward, 11, volt); } void buttonL1Released() { Intake.stop(); } void buttonL2Pressed() { Intake.spin(reverse, 11, volt); intakeOn = true; if (Controller1.ButtonB.pressing()){ curveDrive = !curveDrive; if (curveDrive) { printControllerSetup(); Controller1.Screen.print("Curve Drive Active"); } else { printControllerSetup(); Controller1.Screen.print("Linear Drive Active: "); } } } void buttonL2Released() { Intake.stop(); intakeOn = false; } void buttonUpPressed() { elevationActive = !elevationActive; if (elevationActive) { ElevationPiston.set(true); } else { ElevationPiston.set(false); } } void buttonDownPressed() { scraperActive = !scraperActive; if (scraperActive) { Scraper.set(true); } else { Scraper.set(false); } } void buttonLeftPressed() { //recalibrate inertial Inertial.calibrate(); int calibrateTimer = 0; while (calibrateTimer < 200) { if (!Inertial.isCalibrating()) { printControllerSetup(); Controller1.Screen.print("Recalibrated"); break; } calibrateTimer++; wait (20, msec); } } void setLeftDrive(int velocity1) { Left1.setVelocity(velocity1, percent); Left2.setVelocity(velocity1, percent); Left3.setVelocity(velocity1, percent); } void setRightDrive(int velocity1) { Right1.setVelocity(velocity1, percent); Right2.setVelocity(velocity1, percent); Right3.setVelocity(velocity1, percent); } void buttonRightPressed() { //Automatically balance the robot ElevationPiston.set(true); auton = true; Left1.spin(forward); Left2.spin(forward); Left3.spin(forward); Right1.spin(forward); Right2.spin(forward); Right3.spin(forward); setLeftDrive(90); setRightDrive(90); wait(200, msec); setLeftDrive(40); setRightDrive(50); wait(400, msec); setLeftDrive(40); setRightDrive(-80); wait(200, msec); Left1.stop(); Left2.stop(); Left3.stop(); Right1.stop(); Right2.stop(); Right3.stop(); auton = false; } void checkOverheating() { //check for overheating in any of the motors if (Left1.temperature(percent) > 60 || Left2.temperature(percent) > 60 || Left3.temperature(percent) > 60 || Right1.temperature(percent) > 60 || Right2.temperature(percent) > 60 || Right3.temperature(percent) > 60 || Kicker.temperature(percent) > 60) { if (overHeatingTimer == 0) { Controller1.rumble(rumbleLong); printControllerSetup(); Controller1.Screen.print("Real Overheating Warning"); overHeatingTimer++; } else { overHeatingTimer++; if (overHeatingTimer > 750) overHeatingTimer = 0; } } } int kickerLoop() { //shoot the kicker when there is a triball and keep it loaded at all times bool reachedBottom = false; while (true) { //check if it is optical sensor mode wait(20, msec); if (kickerOn) { KickerLED.on(); if (KickerDrawback.objectDistance(mm) < 90) { if (KickerDistanceSensor.objectDistance(mm) < 40) { //triball detected Kicker.spin(reverse, 11, volt); } else { //no triball detected Kicker.stop(); } reachedBottom = true; } else { Kicker.spin(reverse, 11, volt); reachedBottom = false; } } else { Kicker.stop(); KickerLED.off(); } } return 0; } int intakeLoop() { //spin at 3 volts when the efficency is 0 while (true) { //check if the intake is on wait(20, msec); if (intakeOn) { if (Intake.efficiency(percent) < 10) { //if the intake is on and efficency is low, there is likely a triball in there; reduce the voltage to lower strain on the motor Intake.spin(reverse, 2, volt); } else { //otherwise, spin normally Intake.spin(reverse, 11, volt); } } } return 0; } void init() { //initialize settings, variables, and callback functions Kicker.setStopping(coast); Left1.setStopping(coast); Left2.setStopping(coast); Left3.setStopping(coast); Right1.setStopping(coast); Right2.setStopping(coast); Right3.setStopping(coast); KickerLED.off(); //other functions Controller1.ButtonX.pressed(buttonXPressed); Controller1.ButtonY.pressed(buttonYPressed); Controller1.ButtonR2.pressed(buttonR2Pressed); Controller1.ButtonB.pressed(buttonBPressed); Controller1.ButtonL1.pressed(buttonL1Pressed); Controller1.ButtonL1.released(buttonL1Released); Controller1.ButtonL2.pressed(buttonL2Pressed); Controller1.ButtonL2.released(buttonL2Released); Controller1.ButtonUp.pressed(buttonUpPressed); Controller1.ButtonDown.pressed(buttonDownPressed); Controller1.ButtonLeft.pressed(buttonLeftPressed); Controller1.ButtonRight.pressed(buttonRightPressed); //start task task myTask2 = task(kickerLoop); task myTask3 = task(intakeLoop); } void pre_auton(void) { init(); Inertial.calibrate(); } void usercontrol(void) { auton = false; while (1) { driveCode(); wait(20, msec); } } int main() { // Initializing Robot Configuration. DO NOT REMOVE! vexcodeInit(); // Set up callbacks for autonomous and driver control periods. Competition.autonomous(autonomousProgramTask); Competition.drivercontrol(usercontrol); // Run the pre-autonomous function, basically initialize pre_auton(); // Prevent main from exiting with an infinite loop. while (true) { checkOverheating(); //printController(Intake.efficiency(percent)); wait(20, msec); } } Design Constraints Design Constraints The robot has to be built according to the rules and constraints that the REC foundation lists in the game manual. Some of these robot design constraints are listed: * Robots must start the match no larger than an 18” by 18” by 18” cube. * Robots must be built from VEX official metal, motors, microcontrollers, and wires. * Robots can use limited polycarbonate; the maximum amount is that which could be cut from a single 12” by 24” sheet up to 0.070” thick. * Robots can use no more than 88W of total motor power--large motors are 11W each and small motors are 5.5W each. * Robots can use no more than 2 pneumatic air tanks (unlimited pneumatic pistons). * Robots must have license plates with a clearly identifiable team number. Game Analysis Over Under Game Analysis Now, we will analyze the game to explore what an effective robot design will be able to do, so we can design our robot accordingly. Initial Thoughts This game has many interesting features, that distinguish if from previous challenges: * About 74% (44 / 60) of the primary game objects are match loads. This means that efficient match loading will be key to success. * There is a large barrier in the middle of the field. Going over this barrier will most likely be a huge advantage, as it allows for better maneuverability around the field. * The highest elevation tier is above the height of the elevation bar, so reaching it will require an alliance partner with a compatible design. * Since the AWP tasks require both removing a triball from the match load zone and scoring an alliance triball in an alliance’s goal, and crossing to the opposing offensive zone is not permitted during autonomous, no solo AWP program is possible this year. Both robots will have to be able to complete their respective tasks for that alliance to earn the AWP. Scoring Analysis Points can be obtained from one of three methods: 1. 1. Alliance Triballs can be scored in an offensive zone for 2 points each or a goal for 5 points each 2. 2. Elevating gives between 5 and 20 points, based on the relative elevation tier of the robot. 3. 3. The winner of the Autonomous Bonus earns 8 points. Here is a breakdown of the points earned from a single object (where applicable) for each of the scoring methods. We can observe that elevation gives the most points, and triballs in offensive zones give the least amount of points. However, we also have to consider the total score: * There are 60 triballs, and all 60 can be scored in an offensive zone for 120 points * Around 40 triballs can fit in a goal, for a total of 200 points * Elevating at the highest tier results in 20 points * The Autonomous Bonus gives 8 points In terms of total score, triballs scored in goals give the most points and the Autonomous Bonus and elevation give the least amount of points. Strategy Analysis Here we will list potential strategies of a single robot and analyze the advantages and disadvantages of each one. Push triballs into the goal Advantages Disadvantages * Scores 5 points for each triball pushed in * Makes it harder for the opposing alliance to descore the triballs * Triballs can be descored if one’s alliance is double-zoned * Only a net gain of 3 points if the triballs are already in one’s offensive zone Push triballs into the offensive zone Advantages Disadvantages * Scores 2 points per triball * If the triball was previously in the other offensive zone, then there is a net gain of 4 points * Gets the triball closer to the goal * Triballs can be descored very easily * The barrier may prevent pushing triballs across the center of the field Elevate at the end of the match Advantages Disadvantages * Worth more points if the robot is higher than all other robots * Relatively quick method of scoring * Only practical in the last 10 seconds of the match. * Gives opponents a chance to score more triballs uncontested Launch match load triballs over the barrier Advantages Disadvantages * Scores 2 points per triball * Uses match loads effectively * Allows alliance partner to score these triballs in the goal more easily * Defense may prevent easy loading of triballs onto the robot * Triballs may be descored by the opposing alliance Defend opponent robots that are scoring triballs in goals Advantages Disadvantages Prevents opposing alliance from scoring easily Can simultaneously push triballs to the offensive zone for 2 points Potential SG8.b rule violation Less time to score triball in one’s own goal or elevate Push opponent robots onto the barrier Advantages Disadvantages Disrupts the opponents from scoring quickly Has a chance of legally getting the opponent robot stuck Less time for offensive gameplay Robot has a chance of getting stuck on the barrier Descore triballs from the opponent’s goal Advantages Disadvantages * Has the potential to descore many points from the opposing alliance * Can be done fairly quickly, leaving time for other aspects of the game * Only permissible if the opposing alliance is double-zoned * Triballs still end up on the opponents offensive zone, and count for 2 points for the other team. Over Under Rules Game Introduction The game for this year is VEX Over Under! *All images in this section are from the VEX Over Under Game Manual and property of the RECF Goals in VEX Over Under: * Score triballs in goals or offensive zones. * Elevate your robot at the end of the match * Prevent the opposing alliance from scoring points. The primary game objects are triballs: * Height : 6.18” * Width: 6.18” * Weight: 110 ± 20 grams * Outer diameter: 7.00” Triballs can be scored as such: Triball scored in Goal 5 points Triball scored in Offensive Zone 2 points Next, Goals, where triballs can be scored, have the following dimensions: * Width: 23.08” * Length: 47.13” * Height: 5.78” One important implication is that the triballs are taller than the height of the goal, so the bars on the goal will have to flex upwards slightly for the triballs to go into the goal. Next, we have the Elevation Bars; an alliance can Elevate at the end of match on these to gain extra points: Dimensions of the Elevation Bars: * Outer diameter: 2.38” * Height of horizontal bar: 11.63” from the ground * Height of vertical bar: 30.23” * Horizontal bar length: 21.89” The Barrier also presents an additional obstacle for navigating the field, and is divided into the short barrier and the long barrier. The barrier is constructed out of 2.38” OD PVC pipe raised 0.5” above the field tiles. The Match Load Bars separate the match load zone from the rest of the field: Note that the bars have the same outer diameter as the barrier and the elevation bars, 2.38” The Autonomous Line marks the edges of the neutral zone. It is highlighted below: Game Scoring Definitions Triballs: A triball is Scored in a Goal (for 5 points) if at least two of the four “corners” of the triball are within the outer edges of the PVC pipes enclosing the goal. The triball shaded green is scored, but the one shaded red is not scored because only one corner is within the Goal A triball is Scored in an Offensive Zone (for 2 points) if it is contacting the gray foam tiles in that Offensive Zone. Alliance Triballs count as scored for the alliance that they are colored, regardless of which goal or offensive zone they end the match in. Elevation: A Robot is Elevated if they are contacting their alliance’s elevation bars or the barrier, or their alliance partner. A Robot cannot be elevated if they are contacting the gray foam tiles, the field perimeter, or the yellow elevation bar cap. A Robot is assigned an Elevation Tier based on how high the lowest point on the robot is elevated, as determined using the Height Guide. The Robot with the highest elevation tier will receive 20 points; the second-highest tier will receive 15 points, and so on: The Height Guide along with accompanying measurements for each Elevation Tier ↗ Autonomous: The alliance that scores more points during the Autonomous Period (0:15) will earn an additional Autonomous Bonus of 8 points going into the Driver controlled period (1:45). Elevation points do not count towards determining the winner of the Autonomous Bonus. If an alliance: Removes the triball from that alliance’s math load zone that coincides with their starting tiles Scores at least one alliance triball in their own goal Touches their own elevation bar at the end of the autonomous period Then they can earn an Autonomous Win Point (AWP), which counts as half of a win in the ranking system. Specific Game Rules Robots must be placed on the starting tiles below, and not contacting the barrier, another robot, or any green triballs. Robots may not horizontally expand more than 36” at any point during the match. Triballs should stay in the field. Any triball that comes to rest on the net of a goal may be removed and used as a match load. Each robot gets one alliance triball as a preload. Robots that become entangled in the net will be disabled. Match loads may be introduced by: Placing them into the match load zone Placing them onto a robot that is contacting the match load bar Possession is limited to 1 triball. When the opposing alliance is double-zoning, robots are permitted to go under the opposing alliance’s goal. An alliance is double-zoned if both robots are contacting the gray foam tiles within a single offensive zone, and neither one is contacting the long barrier. In this picture, the red alliance is double-zoned since both robots are in the same offensive zone, and the blue alliance can go under the red goal to descore triballs. Robots are not permitted to contact the gray foam tiles on the opposite side of the location that they start the match in during the autonomous period. Teams are responsible for the actions of their robots at all times, even in interactions with other robots in the neutral zone during autonomous. Robots may not contact opposing robots or the opposing alliance’s elevation bars during the last 30 seconds of the match.