RobotC Tutorial Beginners 1

61
FTC Programming RobotC Programming Making your robot move… Eric and Christina Grajales Mentor Exploding Bacon / DITU FTC Teams 1902 / 5454

description

robotc description

Transcript of RobotC Tutorial Beginners 1

Page 1: RobotC Tutorial Beginners 1

FTC Programming

RobotC ProgrammingMaking your robot move…

Eric and Christina Grajales

Mentor Exploding Bacon / DITU

FTC Teams 1902 / 5454

Page 2: RobotC Tutorial Beginners 1

FTC Programming

Agenda• What is RobotC• Diagram your Robot• RobotC Setup and Configuration• How to display text• Your first program• Reading the joystick• Moving your robot• Servos• Timing• Sensors• Encoders• Useful Links• Questions

Page 3: RobotC Tutorial Beginners 1

FTC Programming

What is RobotCIndustry Standard ‘C’ Programming

Language

Interactive Run-Time Debugger

High Performance Firmware

Programming Development Environment

Training and Curriculum Support

Complete and Total Solution for User Program Development

+

+

+

+

Language extensions for robotics Built-in variables for robotics

devices

RobotC has 100s of already built functions to make programming your robot easier

Page 4: RobotC Tutorial Beginners 1

FTC Programming

Diagram your Robot

• How many Tetrix Motor Controllers are you using?

• How many Tetrix Servo Controllers are you using?

• How many NXT motors?

• What Sensors are you using?

Page 5: RobotC Tutorial Beginners 1

FTC Programming

Diagram your Robot (cont)

• Good time to build an electrical wiring diagram.• All this information is great for your engineering

notebook

Page 6: RobotC Tutorial Beginners 1

FTC Programming

Diagram your Robot (cont)

• Draw your configuration on paper• Name each motor, servo, sensor. Use names that

describe each part and what it does:frontRightMotorfrontLeftMotor, pincherServoLeft, etc

Page 7: RobotC Tutorial Beginners 1

FTC Programming

Lets Build a Test Platform

• 1 Hitechnic Motor Controller• 1 Hitechnic Servo Controller• 2 Tetrix12 V Motors• 1 Tetrix Servo• 1 Lego Motor• 1 Lego Light Sensor• 1 Lego NXT with batteries• 1 Tetrix Battery and Switch• At least 1 Joystick Controller• Laptop • USB, Bluetooth, Samantha connection• Cables and connectors

Page 8: RobotC Tutorial Beginners 1

FTC Programming

Test Platform Wiring Diagram

Page 9: RobotC Tutorial Beginners 1

FTC Programming

RobotC Setup and Configuration

• 1st time setup• Install and RobotC • Turn on NXT and connect NXT to computer via USB cable• Download latest firmware (V2.25 - NXT0819.rfw)

• Note: If you upgrade from an older version of ROBOTC, make sure you upgrade your firmware as well.

• Link via USB, name the NXT your team number• Disconnect USB Cable

• Set RobotC platform type (NXT + Tetrix)

Page 10: RobotC Tutorial Beginners 1

FTC Programming

RobotC Setup

The first time you fire up the ROBOTC IDE, there are a few quick things you will want to do before you begin programming a FTC robot.

1. Set menu level from basic to “Expert”.

a. Window, Menu Level, Expert

2. Set platform type to “LEGO Mindstorms NXT + TETRIX”.a. Robot, Platform Type, LEGO Mindstorms NXT + TETRIX

Page 11: RobotC Tutorial Beginners 1

FTC Programming

FirmwareDownload latest firmware to NXT brick.

* Note that this only needs to be done the first time you setup a new NXT brick with ROBOTC and when you upgrade your version of ROBOTC.

** Also note that the battery level must be high enough on the NXT before it will allow you to download new firmware.

a. Make sure NXT is connected via USB and turned on.

b. Open Link Setup dialog

i. Robot, NXT Brick, Link Setup

c. Select NXT in top left corner and press “F/W Download” button.

d. Select .rfw file in default firmware directory in popup and press “Open”.

i. For ROBOTC v2.03, the firmware file should be: “NXT798.rfw”.

e. After a few moments, the Link Setup dialog box will display some verbose information in the Message Log and your NXT should beep several times and restart. When complete, you should see a series of messages similar to below in the Message Log:

Page 12: RobotC Tutorial Beginners 1

FTC Programming

Exercise RobotC Setup and

Configuration• Robot C Setup

• Link via USB, Bluetooth, or Samantha to NXT

• Open the Sample program “C:\Program Files\Robotics Academy\ROBOTC for MINDSTORMS\Sample Programs\NXT\LCD Examples\NXT Draw Spiral.c”

• “Compile and Download” sample program to your NXT.

• Run the sample program.

Page 13: RobotC Tutorial Beginners 1

FTC Programming

Tetrix Ranger

Page 14: RobotC Tutorial Beginners 1

Get to Configuration Window

FTC Programming

Page 15: RobotC Tutorial Beginners 1

FTC Programming

Textrix Controller Setup

Page 16: RobotC Tutorial Beginners 1

FTC Programming

Motor Setup

Page 17: RobotC Tutorial Beginners 1

FTC Programming

Sensor Setup

Page 18: RobotC Tutorial Beginners 1

FTC Programming

RobotC Pragma Setup#pragma config(Hubs, S1, HTMotor, HTServo, none, none)#pragma config(Sensor, S1, touch, sensorI2CMuxController)#pragma config(Sensor, S2, compass, sensorVirtualCompass)#pragma config(Sensor, S3, light, sensorLightActive)#pragma config(Sensor, S4, sonar, sensorSONAR)#pragma config(Motor, mtr_S1_C1_1, leftMotor, tmotorNormal, openLoop, encoder)#pragma config(Motor, mtr_S1_C1_2, rightMotor, tmotorNormal, openLoop, reversed, encoder)#pragma config(Servo, srvo_S1_C2_1, servo1, tServoStandard)#pragma config(Servo, srvo_S1_C2_2, servo2, tServoNone)#pragma config(Servo, srvo_S1_C2_3, servo3, tServoNone)#pragma config(Servo, srvo_S1_C2_4, servo4, tServoNone)#pragma config(Servo, srvo_S1_C2_5, servo5, tServoNone)#pragma config(Servo, srvo_S1_C2_6, servo6, tServoNone)//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//

Page 19: RobotC Tutorial Beginners 1

FTC Programming

Exercise

• Setup the Ranger Configuration in RobotC

Page 20: RobotC Tutorial Beginners 1

FTC Programming

Task Main• Task main is used to tell the NXT where the beginning of your programs is.

• The beginning and end of “task main” is denoted with curly braces “{ }”

• When the program execution reaches the end of the main task, all robot activity stops.

#include "JoystickDriver.c" // Tells ROBOTC to include the driver file for the joystick. task main() // All programs must have this task{ while(true) { motor[rightMotor] = joystick.joy1_y1; motor[leftMotor] = joystick.joy1_y2; }}

Page 21: RobotC Tutorial Beginners 1

FTC Programming

Variables• Variables are the robot’s way of storing values for later use. They function as containers

or storage for values. Values such as sensor reading can be placed in a variable and retrieved at a later time for convenient use. A variable is simply a place to store a value.

Useful types:• Integer, or “int” values are numbers with no fractional or decimal component.• Floating point (“float”) numbers are so called because the decimal point “floats” around

in the value, allowing decimal places to be used.• Strings (“string”): Text in ROBOTC is always a “string”. In ROBOTC, the word “Hello” is

really a collection of letters – ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ – “strung” together to form a single value.• Boolean (“bool”) values represent “truth” or “logic” values, in the form of “true” or “false”.

Use variable names that make sense. What is more readable?

a = b / c; Or speed = distance / time;

Page 22: RobotC Tutorial Beginners 1

Conditional Statements• If statements are pretty self explanatory. If a, then b.• The syntax (grammar of programming) of an if statement is

If(4 < 100) {

Do stuff;

}

• If else statements run if the if statement was false. These are useful for when there are multiple cases of an instance.

else if (4 == 100) {

Do stuff;

}

• Else statements follow the if before it. If the if statement was false then the else statement will run.

else {

Do stuff;

}

FTC Programming

Page 23: RobotC Tutorial Beginners 1

Boolean Logic

• == equals• < less than• > greater than• <= less than or equal to• >= greater than or equal to• && and• || or

• NO (0 < a < 100)!!!! Use &&!

((0 < a) && (a < 100))

FTC Programming

Page 24: RobotC Tutorial Beginners 1

Loops• For loops run a certain number of times

(in this case, 10).• Be careful of infinite loops (i--)

For (int i = 0; i < 10; i++;)

{

code that will repeat;

}

FTC Programming

Page 25: RobotC Tutorial Beginners 1

Loops (cont.)• While statements are used when you don’t know how many times

the code will run.

While (true)

{

do stuffffffffs;

}• Do While statements always run at least once, and then follow the

while loop.

Do

{

more stuffffffssss;

}

While(true)

FTC Programming

Page 26: RobotC Tutorial Beginners 1

FTC Programming

CommentsTwo ways to comment code:

• Comments: // A single line • Comments: /* Section of code */

• Comment your code, next year when you read the code you’ll know what you did and why.

// Move motor C forward with 100% powertask main(){ int motorspeed;

/* Motor C forward with 100% power Do this for 3 seconds */ motorspeed = 100; motor[motorC] = motorspeed; wait1Msec(3000);}

Page 27: RobotC Tutorial Beginners 1

FTC Programming

How to display textDisplay text functions:• eraseDisplay() - Erases the complete NXT LCD display• nxtDisplayClearTextLine(nLineNumber) • nxtDisplayCenteredTextLine(nLineNumber, sString) • nxtDisplayCenteredTextLine(nLineNumber, sFormatString, parm1, parm2) • nxtDisplayString(nLineNumber, sFormatString, parm1, parm2, parm3) • nxtDisplayTextLine(nLineNumber, sFormatString, parm1, parm2, parm3) • nxtDisplayTextLine(nLineNumber, sString) Where nLineNumber is the NXT LCD line number and sFormatString

specifier Output Example Code Example Output %d Signed decimal integer "%d" 4246%f Decimal floating point "%f" 3.14159 %s String of characters "%s" ROBOTC

Page 28: RobotC Tutorial Beginners 1

sFormatString Example

• Read raw and normal light sensor data on the NXT

• If you want to print “Raw: 333 Normal: 96”

sFormatString will look like

“Raw: %d Normal: %d”

• Param1 and Param2 are variables, in this case the raw and normalized light sensor data. Generally, these are constructed in the beginning of the code with names like rawLightData and normalLightData.

• nxtDisplayTextLine(2, “Raw: %d Normal: %d”, rawLightData, normalLightData);

FTC Programming

Page 29: RobotC Tutorial Beginners 1

FTC Programming

How to display text (cont)

When using FTC Template the NXT LCD displays Field Management System (FMS) information used by the Field Technical Advisor during competitions.

• Line 0 NXT status line (do not touch) – Battery Status, Bluetooth enabled, etc• Line 1 FCS Mode (Waiting, Auto, Teleop)• Line 2 BLANK• Line 3 External Battery Voltage (Textrix 12 Volt battery)• Line 4 NXT Battery Voltage• Line 5 FMS Msgs count• Line 6 "Teleop FileName:"• Line 7 NXT Teleop file name

Items in bold are refreshed every 200ms. DO NOT OVERWRITE THESE LINES!

Page 30: RobotC Tutorial Beginners 1

FTC Programming

How to display text (cont) Sample Program

task main(){

int int_test = 1234; float float_test = 3.14159; eraseDisplay(); // Clear out the NXT LCD Screen

nxtDisplayCenteredTextLine(2, “Hello”); nxtDisplayTextLine(3, “Data %d %f”, int_test, float_test); wait1Msec(5000); // Wait 5 seconds

}

•“Compile and Download” sample program to your NXT.

•Run the sample program.

Page 31: RobotC Tutorial Beginners 1

Exercise

• Using the example on the previous slide, compile and run the code on the virtual world robot.

FTC Programming

Page 32: RobotC Tutorial Beginners 1

FTC Programming

Joystick Controller• Logitech PS2 type controller• 2 Joysticks• 10 Buttons• Access Joystick via built in functions:

joystick.joy1_x1joystick.joy1_y1joystick.joy1_x2joystick.joy1_y2

return integer ranges between -127 and 127joy1Btn(button) // (button 1 thru 10)

returns the a value of 1 (true) if pressed and a value of 0 (false) if not pressed. 

• Similar functions for Joystick2.• Must “#include "JoystickDriver.c "“ in your

program

Page 33: RobotC Tutorial Beginners 1

FTC Programming

Joystick Controller (cont)Sample 1

#include "JoystickDriver.c"     // Tells ROBOTC to include the driver file for the joystick.task main(){ while(true) { if (joy1Btn(1))                   // If Joy1-Button1 is pressed:    {      motor[motorA] = 100;       // Turn Motor A On at full power    }    else                            // If Joy1-Button1 is NOT pressed:    {      motor[motorA] = 0;            // Turn Motor A Off    }  }}

Sample 2#include "JoystickDriver.c" // Tells ROBOTC to include the driver file for the joystick. task main(){ while(true) { motor[motorC] = joystick.joy1_y1; motor[motorB] = joystick.joy1_y2; }}

Page 34: RobotC Tutorial Beginners 1

Tank Drive

FTC Programming

Forward Right

Backward

Page 35: RobotC Tutorial Beginners 1

FTC Programming

Move Simple BotTank Mode - uses both left and right joysticks to drive the

robot.

void tank(int y1, int y2){

motor[motorC] = y1;motor[motorB] = y2;

}

task main(){ while (true) { tank(joystick.joy1_y1, joystick.joy1_y2); }}

Arcade Mode – only one joystick as controller

// uses x1 and y1 from joystick1void arcade(int x, int y) { int powY; int powRightMotor; int powLeftMotor;

powY = y; if (x < 0) // if x negative, turning left; otherwise, turning right { powLeftMotor = (powY * (128 + (2 * x))/128); // left motor reduced for right turn powRightMotor = powY; // right motor not changed } else { powRightMotor = (powY * (128 - (2 * x))/128); // right motor reduced for left turn powLeftMotor = powY; // left motor not changed }

motor[motorC] = powLeftMotor; motor[motorB] = powRightMotor;}

task main(){ while (true) { arcade(joystick.joy1_x1, joystick.joy1_y1); }}

Page 36: RobotC Tutorial Beginners 1

FTC Programming

Improving Drive CodeWhile the Tetrix motors accept an output power range of 100 to +100, the analog sticks on the joystick return values between -128 to +127. This means if the analog stick is in the range under -100 or over +100, the value passed to the motor is simple transformed to -100 or +100. This is less than ideal because it reduces the usable range of the analog stick by about 20%.

There is another issue related to dead zones within the physical joysticks themselves. Due to inaccuracies and tolerances within the manufacturing process, the analog sticks on most FTC joysticks will rarely return to a perfect zero when released. This has a tendency to cause a robot to slowing spin in a circle when no one is touching the analog sticks. A simple code solution is to account for a dead zone at low values for the analog sticks which can then be treated as zero.

The basic formula: motorValue = (joystickValue / Max joystickValue) * max motorOutput

int scaleForMotor(int joyvalue){ const int DEADZONE = 5; const int MAX_MOTOR_VAL = 100; const float MAX_JOY_VAL = 127.0;

if (abs(joyValue) < DEADZONE) { // Check if joystick value is return 0; // less than deadzone } // Scale joystick value float ratio = joyValue / MAX_JOY_VAL; int scaledVal = ratio * MAX_MOTOR_VAL;

// return scaled value return scaledVal;}

A logarithmic scale to get fine grain control at lower speeds and quickly scale the power up at the end of the range. motorValue = (joystickValue^2 / Max joystickValue^2) * max motorOutput

int scaleForMotor(int joyvalue){ const int DEADZONE = 5; const int MAX_MOTOR_VAL = 100; const float MAX_JOY_VAL = 127.0;

if (abs(joyValue) < DEADZONE) { // Check if joystick value is return 0; // less than deadzone } // Scale joystick value int direction = joyValue / abs(joyValue); float ratio = (joyValue * joyValue) / (MAX_JOY_VAL * MAX_JOY_VAL); int scaledVal = ratio * MAX_MOTOR_VAL * direction;

// return scaled value return scaledVal;}

Page 37: RobotC Tutorial Beginners 1

FTC Programming

Motor Control

0

10

20

30

40

50

60

70

80

90

100

1 13 25 37 49 61 73 85 97 109 121

Joystick Value

Mo

tor

Ou

tpu

t

Simple

Logarithmic

Page 38: RobotC Tutorial Beginners 1

FTC Programming

Move your Robot Sample#include "JoystickDriver.c"     // Tells ROBOTC to include the driver file for the joystick.

void tank(int y1, int y2){

motor[LeftMotor] = y1;motor[RightMotor] = y2;

}

int scaleForMotor(int joyvalue){ const int DEADZONE = 5; const int MAX_MOTOR_VAL = 100; const float MAX_JOY_VAL = 127.0;

if (abs(joyValue) < DEADZONE) { // Check if joystick value is return 0; // less than deadzone } // Scale joystick value float ratio = joyValue / MAX_JOY_VAL; int scaledVal = ratio * MAX_MOTOR_VAL;

// return scaled value return scaledVal;}

task main(){ while (true) { tank(scaleForMotor(joystick.joy1_y1), scaleForMotor(joystick.joy1_y2)); }}

Page 39: RobotC Tutorial Beginners 1

FTC Programming

Exercise

• Move your Robot• Write code to move the 12V tetrix motors with your

joystick.• Compile and download it to your NXT• Run the code and move your joystick to see the motors

turn.

Page 40: RobotC Tutorial Beginners 1

What is a Servo?

• There are two types of servos: Standard Servos and Continuous Rotation Servos (almost like a super low powered motor).

• An example of when to use a standard servo would be the balance bridges from the FTC 2010 game. Many teams had a metal arm that would lower the bridge so that the robot could cross it. (Think moving in arcs)

FTC Programming

Page 41: RobotC Tutorial Beginners 1

FTC Programming

Servos• servoValue[servo#] - Standard Servo Only

This read-only function is used to read the current position of the servos on a sensor port Servo controller. Values can range from 0 to 255. Center Point value 127. The value returned in this variable is the last position that the firmware has told the servo to move to. This may not be the actual position because the servo may not have finished the movement or the mechanical design may block the servo from fully reaching this position. To set the position of a servo, use the "servoTarget" or "servo" functions.

• servo[servo#] = position or servoTarget[servo#] = position;

This function is used to set the position of the servos on a sensor port Servo controller. Values can range from 0 to 255. The firmware will automatically move the servo to this position over the next few update intervals. (Be sure to give the servo some amount of time to reach the new position before going on in your code.)

• servoChangeRate[servo#] = changeRate; Specifies the rate at which an individual servo value is changed. A value of zero inidcates servo will move at maximum speed. The change rate is a useful variable for "smoothing" the movement of the servos and preventing jerky motion from software calculated rapid and wide changes in the servo value. The default value is a change rate of 10 positions on every servo update which occurs. (updates occur every 20 milliseconds)

Page 42: RobotC Tutorial Beginners 1

FTC Programming

Servos Sample#include "JoystickDriver.c"     task main(){ while(true) { if (joy1Btn(1))           // If Joy1-Button 1 is pressed:    {      servoTarget[1] = 255; // Turn servo clockwise    }

else if (joy1Btn(3))         // If Joy1-Button 3 is pressed: {       servoTarget [1] = 0; // Turn servo counter clockwise

}    else                               {      servoTarget [1] = 127; // Center servo    }  }}

Page 43: RobotC Tutorial Beginners 1

FTC Programming

Exercise

• Move your Servo• Write code to move the servo using a joystick button

joystick.• Compile and download it to your NXT• Run the code and press the joystick to see the servo

turn.

Page 44: RobotC Tutorial Beginners 1

FTC Programming

TimingFunctions to pause the program for a desired amount time:

wait1Msec(nMSec);wait10Msec(nTenMSec); • Program execution will wait for the specified number of clock units. Units can be in either 1-

millisecond or 10-millisecond counts. The maximum interval that can be specified is either 32.767 seconds or 327.67 seconds depending on which function is used.

There are four timers (T1, T2, T3 and T4) the user can program. These four timers can be individually be reset to zero within a program. Theses timers are useful for measuring elapsed time of events.

ClearTimer(theTimer);• Timers start counting as soon as the NXT is powered on. A user's program should reset a timer

before using it, so use this function to reset the value of the specified timer to zero.

time1[theTimer], time10[theTimer], time100[theTimer]• These three arrays hold the current value of the respective timers. Each of the timer values can

be retrieved in units of 1, 10 and 100 milliseconds depending on which array is used. For example, time1[T1] retrieves the value of timer T1 in units of 1-msec and time10[T1] retrieves the value using a 10-msec tick.

Page 45: RobotC Tutorial Beginners 1

FTC Programming

Timing Sample

#include "JoystickDriver.c"    

task main()

{ ClearTimer(T1); // Resets Timer T1 to 0

while(time1[T1] < 5000) // Loop for 5 seconds

{

// do something in loop

wait1Msec(500); // Wait ½ second

  }}

Page 46: RobotC Tutorial Beginners 1

Types of Sensors

• Light Sensor• Detects amount of light (grayscale); two modes: with flashlight

and without

• Touch Sensor• Detects if the sensor hit something

• Ultrasonic/Sonar Sensor• Detects how far an object is from the sensor

• Gyro• Detects angle based off initialized 0

• Compass• Detects True North

FTC Programming

Page 47: RobotC Tutorial Beginners 1

FTC Programming

SensorsSensorType[] – • The SensorType array is used to specify what type of sensor is connected

to a certain port. Most users should not have to use this functionality and should use the Motors and Sensor Setup instead.

Example: SensorType[sonarSensor] = sensorSonar;

SensorRaw[] • This array value will return the "raw" (un-normalized) value of a sensor.

Usually this is the raw A-D converted value, which is an analog value between 0 to 1023.

SensorValue[]• This array value returns the value of the sensor in a normalized fashion.

Rather than returning a raw value of 0 to 1023, ROBOTC will interpret the data from the "SensorType" and return a more accurate representation of the sensor's data. An example of this is the Light Sensor, which will return a percentage value from 0 to 100.

Page 48: RobotC Tutorial Beginners 1

FTC Programming

Sensor Sample

#include "JoystickDriver.c"     task main(){

wait1Msec(50); //the program waits 50 millisecond to initialize the light sensor

// 0 black, 100 white while(SensorValue[lightSensor] > 80) //keep looping while the light sensor's value is greater than 80. { motor[leftMotor] = 75; //leftMotor is run at a 75 power level motor[rightMotor] = 75; //rightMotor is run at a 75 power level }

motor[leftMotor] = 0; //leftMotor is stopped motor[rightMotor] = 0; //rightMotor is stopped}

Page 49: RobotC Tutorial Beginners 1

Exercise

• Using the previous Light Sensor sample• Compile and run inside Virtual World• Use the “Learning RobotC Tables”• In VW, select the Utilities Tab, Light Sensor Table,

Position F to run the example.

FTC Programming

Page 50: RobotC Tutorial Beginners 1

FTC Programming

Tetrix Motor Encoders

Enables your robot to move a fixed distance, rotate to a specific position, or move at a constant speed.

The technique to measure the movement of your robot is called odometry, it requires an encoder that translates the turns of the wheel into the corresponding traveled distance.

The Tetrix Encoder measures rotation 1440 ticks per revolution – if robotis geared you will need to compute gear reduction factor and wheel size to computer distance travelled per encoder tick.

Page 51: RobotC Tutorial Beginners 1

FTC Programming

Tetrix Motor Encoders

• Assuming direct drive and 4 inch wheel, 1 rotation of the motor will move the robot 12.6 inches (Circumference of wheel is = 2 * pi * radius)

• If we want to travel 20 inches, then we need to compute the number of ticks the encoder must measure = (1440 ticks/revolution)/(12.6 inches/revolution) * 20 inches is about 2285 ticks.

Page 52: RobotC Tutorial Beginners 1

FTC Programming

Motor Encoders Functions

nMotorEncoderTarget[] - The nMotorEncoderTarget is used to set a target distance that a motor should move before system puts motor back in idle or stopped state. A target value of 0 (zero) means run forever.

nMotorRunState[] - Array containing the internal state of a NXT motor. Useful in checking when a motor movement "command" has finished. There are three different states - runStateRunning, runStateHoldPosition, runStateIdle.

nMotorEncoder[] – Array containing the current encoder value

Page 53: RobotC Tutorial Beginners 1

FTC Programming

Encoder Sample#include "JoystickDriver.c"    

task main()

{

int rotations = 1440.0 * 20.0 / 12.6;

nMotorEncoder[motorB] = 0; // Reset the Motor Encoder of Motor B.

nMotorEncoderTarget[motorB] = rotations; // Set the target to 5 rotations.

motor[motorB] = 75; // Motor B is run at a power level of 75.

motor[motorC] = 75; // Motor C is run at a power level of 75.

while(nMotorRunState[motorB] != runStateIdle) // While Motor B is still running

{

wait1Msec(50);

}

// or

while (nMotorEncoder[motorB] < rotations) // wait for motor to reach a specific # of ticks

{

wait1Msec(50);

}

motor[motorB] = 0; // Motor B is stopped at a power level of 0.

motor[motorC] = 0;

}

Page 54: RobotC Tutorial Beginners 1

FTC Programming

How to turn accurately• To do a 1 wheel turn, where one side of the robot drivetrain

is stopped, and the other side turns.• Arc Distance = 2 * pi * radius (width of robot) * angle / 360• Then use encoders and their ticks-to-inch ratio from earlier

to calculate the offset of the right encoder from the left one.

Example: An 18 in wide robot would travel how much in a 90 degree turn?

Answer:28.27 inches3240 ticks

before after

Page 55: RobotC Tutorial Beginners 1

FTC Programming

Simplify your Code with Functions

• A function is a self-contained collection of instructions that, when called, accepts a specified number of arguments, performs some task, and returns a value back to the calling program

• Example :moveForward(int num_inches){ int rotations_ticks; float wheel_diameter; wheel_diameter = 4.0;

// 1440.0 is the number of ticks per wheel rotation, if wheels are geared verify this value // (num_inches / wheel perimeter), calculates the number of wheel rotations

rotation_ticks = 1440.0 * num_inches / (wheel_diameter * 3.14159);

nMotorEncoder[motorB] = 0; // Reset the Motor Encoder of Motor B. wait1Msec(10); // always wait some time after setting nMotorEncocder

motor[motorB] = 75; // Motor B is run at a power level of 75. motor[motorC] = 75; // Motor C is run at a power level of 75. while (nMotorEncoder[motorB] < rotations_ticks) // wait for motor to reach a specific # of ticks { wait1Msec(50); } motor[motorB] = 0; // Motor B and C are stopped at a power level of 0. motor[motorC] = 0;}

task main(){ moveForward(30); // call function}

Page 56: RobotC Tutorial Beginners 1

FTC Programming

Functions

• Good set of functions to write for your robot:• moveForward (int num_inches)• turnRight(int num_degrees)• turnLeft(int num_degrees)• MoveBackwards(int num_inches)• scaleForMotor(int joyValue)

Page 57: RobotC Tutorial Beginners 1

FTC Programming

Exercise

• Putting it all together

Page 58: RobotC Tutorial Beginners 1

FTC Programming

Useful References and LinksROBOTC.netThe main website for ROBOTC is one of the best resources for getting help or interacting with other

members of the ROBOTC community. You can email their technical support if you have a technical issue with the software/IDE itself or if you want to report a bug. But often more useful are the forums. There is a sub-forum dedicated to FTC and most posts there are responded to the same day. I personally make an effort to visit the forum daily during the build season as do a number of other mentors. It may be the best place to get help and feedback from a largest number of smart folks familiar with ROBOTC.

Main website: http://www.robotc.net/Forums: http://www.robotc.net/forums/Blog: http://www.robotc.net/blog

Robotics Academy CurriculumRobotics Academy, the non-profit affiliated with Carnegie Melon University who created ROBOTC, offer a

number of training resources. Note that some of these are not free.Main Website: http://www.robotc.net/education/curriculum/nxt/Preview Website : http://www.education.rec.ri.cmu.edu/previews/robot_c_products/teaching_rc_tetrix_preview/

index.htmlClasses: http://www.robotc.net/education/training/nxt/Webinars: http://www.robotc.net/education/webinars/Older videos & tutorials: http://www.education.rec.ri.cmu.edu/content/events/ftc/robotc/index.htm

Tetrix for FTC http://www.tetrixrobotics.com/ftc/

Page 59: RobotC Tutorial Beginners 1

FTC Programming

Useful References and LinksXander’s 3rdParty DriversXander Soldaat is a regular contributor to the NXT community who maintains a set of excellent third

party drivers for NXT compatible sensors. These drivers offer enhanced functionality for using just about any sensor with ROBOTC and I highly recommend them; particularly so if you are using the IR Seeker or Sensor Multiplexer.

3rdParty Drivers: http://rdpartyrobotcdr.sourceforge.net/Blog: http://mightor.wordpress.com/

Chief DelphiFor years, the forums on Chief Delphi have been the most active and engaging source for unofficial

FIRST related information. It is an extremely dynamic online community of FIRST students, mentors, and volunteers. As such, it is another great resource for help with not only ROBOTC, but FTC and FIRST in general.

Main website: http://www.chiefdelphi.com/forums/index.phpFTC sub-forum: http://www.chiefdelphi.com/forums/forumdisplay.php?f=146

Course Notes – Albert Schueller, Whitman CollegeOne of the best ROBOTC tutorials can be found in the class notes from Albert Schuellers’s course on

programming with robots at Whitman College. This is a good read through which covers many of the basics/fundamentals that this guide does not.

PDF of tutorial: http://carrot.whitman.edu/Robots/notes.pdf

Page 60: RobotC Tutorial Beginners 1

FTC Programming

Acknowledgments

1. FTC-Iowa 3-day Coaches Workshop, June 13th to 15th, 2010 – University of Iowa, Supplemental Guide for ROBOTC Programming

2. Programming with Robots, Albert W. Schueller, Whitman College, October 12, 2011

3. Xander’s 3rdParty Drivers

4. Robotics Academy Curriculum

Page 61: RobotC Tutorial Beginners 1

FTC Programming

Questions