RobotC – A Tutorial I

63
RobotC – A Tutorial I

description

RobotC – A Tutorial I. Overview. Basic Introduction to the Programming Software Introduction to Programming Concepts RobotC Specifics ( next lecture). OVERVIEW. Section Overview. Explanation of the Integrated Development Environment (IDE) and its parts Top Menubar Side Functions Panel - PowerPoint PPT Presentation

Transcript of RobotC – A Tutorial I

Page 1: RobotC – A Tutorial I

RobotC – A Tutorial I

Page 2: RobotC – A Tutorial I

Overview

1. Basic Introduction to the Programming Software

2. Introduction to Programming Concepts

3. RobotC Specifics (next lecture)

OVE

RVI

EW

Page 3: RobotC – A Tutorial I

SEC

TIO

N 1 Explanation of the Integrated Development Environment

(IDE) and its parts Top Menubar Side Functions Panel Code Window Error Window

Compile/Download code to the NXT

Run the code

Section Overview

Page 4: RobotC – A Tutorial I

IDE ExplainedSE

TUP

Code Window

Error Window

Side Functions Panel

Top Menubar

Page 5: RobotC – A Tutorial I

IDE Explained – Top MenubarSE

TUP

All Help topics

Variable Help

Debugging help

Web Help

Compile/Run

Debug

Sensor Setup

Firmware Download

Page 6: RobotC – A Tutorial I

IDE Explained – Side Functions PanelSE

TUP

Drag and drop

Explanation of the function

Functions list

Page 7: RobotC – A Tutorial I

IDE Explained – Code WindowSE

TUP

Line Numbers

Color coding to help identify different segments of the code.The colors can be changed from preferences menu In the top menubar

Auto-complete feature

Denotes errors/warnings

Page 8: RobotC – A Tutorial I

IDE Explained – Error WindowSE

TUP

Error line number

Fatal Error Explanation of the cause of the error

Warnings and general info, ignorable messages

Page 9: RobotC – A Tutorial I

Compiling/RunningSE

TUP There are 4 basic steps in running a program

1. Download the firmware (a one-time step) – refer to textbook

2. Compile the program. This reports any errors and warnings

3. Load the program onto the NXT

4. Run program either from debugger window or the NXT directly

Page 10: RobotC – A Tutorial I

Compiling/Downloading Your CodeSE

TUP

To compile AND DOWNLOAD your program, press F5To compile WITHOUT downloading to NXT, press F7

Compile the code

If compilation reports errors, look at the error window and correct the errors. Then try compiling again.

Page 11: RobotC – A Tutorial I

Running Your ProgramSE

TUP

Your program can be run by: Clicking the Start button on the popup window - (if the NXT is connected to the computer)

OR Hitting the Orange button on the NXT – (if NXT is disconnected)

Click the start button(This starts the debugger, covered in the next lecture.)

Page 12: RobotC – A Tutorial I

Basic ExerciseSE

TUP

Typing and running your first program.

Use the steps you know to type the simple hello world program below, save the file and then run the code on the NXT.

Don’t worry if you don’t understand the exact functioning of the program. You should just be able to use the IDE

1

2

3

4

5

6

7

task main ()

{

nxtDisplayTextLine(3, “Hello”);

nxtDisplayTextLine(4, “World”);

while(true);

}

Observe the output on the NXT screen

Page 13: RobotC – A Tutorial I

SummarySE

CTI

ON

SU

MM

AR

YTill now we have learned

Basic IDE features and whereabouts of various options

How to compile, load and run a program.

With this level of familiarity, you should be able to try writing and running the code examples in the next few sections.

Now to see some general programming concepts

Page 14: RobotC – A Tutorial I

SEC

TIO

N 2 Programming Syntax

Capitalization Whitespaces Comments Variables Boolean Algebra

Control Structures Tasks Functions If-Else/Switch While/For

Section Overview

Page 15: RobotC – A Tutorial I

General RulesRobotC is a text-based programming language based on standard C programming language rules

1

2

3

4

5

6

7

8

9

task main ()

{

motor[motorA] = 50;

motor[motorB] = 50;

wait1Msec(2000);

motor[motorA] = -50;

motor[motorB] = -50;

wait1Msec(2000);

}

Code written in proper SYNTAX can be compiled and converted into machine code, which can be loaded onto the robot

See the regularity within the statements.

It follows something called SYNTAX (formatting rules) that RobotC understands

PRO

GR

AM

MIN

G R

ULE

S

Page 16: RobotC – A Tutorial I

KeywordsPR

OG

RA

MM

ING

RU

LES

RobotC has reserved a certain set of words that convey a special meaning to the compilerThese cannot be used for any other purpose throughout the program.

1

2

3

4

5

6

7

task myTask ()

{

int myVar = 50;

motor[motorA] = 50;

motor[motorB] = myVar;

wait1Msec(2000);

}

KEYWORDS –Convey special meaning to the compiler

NOT A KEYWORD

You can use it and name it as you wish

Observe how the software trying to help you by color coding what it recognizes as a reserved word and what it doesn’t

Blue, Red and Black

Page 17: RobotC – A Tutorial I

CapitalizationPR

OG

RA

MM

ING

RU

LES

Using lowercase or UPPERCASE is significant in RobotC

1

2

3

4

5

6

Task myTask ()

{

int myVar = 50;

Int myBadVar = 100;

motor[motorA] = 50;

}

DO NOT REPRESENT the intended meaning

Will result in compiler errors

NOT THE SAME

The first of these represents the keyword for integer.

The second one is an error.

For variable names, it doesn’t matter which case you use if it’s the same throughout the program.

Makes a difference for keywords

Page 18: RobotC – A Tutorial I

StatementsPR

OG

RA

MM

ING

RU

LES

A set of commands make a statement

It may be more than one line or several in one line1

2

3

4

5

6

task myTask ()

{

int myVar = 50;

motor[motorB] = 50

motor[motorA] = 50;

}

SYNTAX ERROR – No semicolon to end the intended statement

Will result in compiler errors

Each of these lines represents one statement

For the compiler, each statement is separated by a semicolon (;)

Page 19: RobotC – A Tutorial I

White spacesPR

OG

RA

MM

ING

RU

LES

White spaces (space, tab, blank lines) are not interpreted by the compiler.

This means that you may use white spaces as per your liking – where you want, how many you want

Use as necessary to organize your code better

This DOES NOT mean that a white space may be used within a keyword or a variable.

in t and int are different

myVar and my Var are different

Page 20: RobotC – A Tutorial I

WhitespacesPR

OG

RA

MM

ING

RU

LES

The only difference in the two codes below is the use of whitespaces. Observe how easy it is to understand the second code as compared to the first one!!

1

2

3

4

5

6

7

8

9

10

11

12

task myTask ()

{

int Reading;

while (true) {

Reading = SensorValue(ls);

if (Reading > 40) {

motor[motorA] = 50;

} else {

motor[motorA] = -50;

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

task myTask ()

{

int Reading;

while (true) {

Reading = SensorValue(ls);

if (Reading > 40) {

motor[motorA] = 50;

} else {

motor[motorA] = -50;

}

}

}

Page 21: RobotC – A Tutorial I

CommentsPR

OG

RA

MM

ING

RU

LES

Commenting a program means using descriptive text to explain portions of code.

It is very important to add good comments as it cuts down confusion for someone else, or even yourself at a later stage

The compiler and robot both ignore comments when running the program.

1

2

3

4

5

6

7

8

task myTask ()

{

/* Modified by Shalabh 12/05

Start motor A first

*/

motor[motorA] = 50;

// Start motor B

motor[motorB] = 50;

Multi line comments. Start by /* and end by */

Single Line comments. Start with a // end when you hit enter/return

Page 22: RobotC – A Tutorial I

CommentsPR

OG

RA

MM

ING

RU

LES

One of the major uses of comments is to hide code from the compiler

During the testing phase, you may not want the compiler to execute the entire code. Comments can be used to achieve this without having to delete lines

1

2

3

4

5

6

7

8

9

10

task myTask ()

{

//motor[motorA] = 50;

motor[motorB] = 50;

/* tempVar = 20;

motor[motorA] = tempVar;

*/

}

If for some debugging purpose, you do not want motor A to operate, you can comment out all statements that have anything to do with motor A.

Easier than deleting and re-typing

Page 23: RobotC – A Tutorial I

PunctuationPR

OG

RA

MM

ING

RU

LES

Punctuation, much like the English language is used to demarcate sections or convey special meaning.

Semicolon (;) – Used to mark the end of statements

Curly Braces { } – Used to mark the beginning and end of control structures

Square Braces [ ] – Used to denote special elements like array elements

Parenthesis ( ) – used to denote special elements like arguments passed to a function, or to define order-of-operations within a mathematical expression.

Observe the usage of these punctuations during various parts of the presentation

Page 24: RobotC – A Tutorial I

VariablesVA

RIA

BLE

S Variables are places to store values (such as sensor readings) for later use, or for use in calculations.

Usage Steps Create/Declare the variable

int demoVar, demoFinal=17;

Assign a value to the variable

demoVar = 10;

Use the variable for calculations or display

demoFinal = demoVar * demoVar;

Datatype

Variable name

Variable being assigned

Variable being used for calculation

Variable being assigned

Variable being used for calculation

Page 25: RobotC – A Tutorial I

Variable RulesVA

RIA

BLE

S There are two rules that must be followed while defining variables

Data Type - Defines the type of value that the variable holds

Data Type Description Example Keyword

Integer Positive and negative whole numbers

-1, 29, 12, 13, 0 int

Floating Point Decimal Values or whole numbers

1.2934, 1.1, -123.23 float

String String of characters “Daniel is a good guy”

string

Boolean A yes or no value true, false or 0, 1 bool

Name Rules:A variable name can not have spaces in itA variable name can not have symbols in itA variable name can not start with a numberA variable name can not be the same as a reserved word

Page 26: RobotC – A Tutorial I

Variable ScopeVA

RIA

BLE

S Variables declared at certain places can only be used within some limited area. This defines the scope of a variable

There are two types of variables

Local: Those that are restricted to a function/task

Global: Those that can be accessed from anywhere

Global

Local Local

main() myTask()

Page 27: RobotC – A Tutorial I

Global variable. Can be used/modified anywhere

Local variable. Can be used/modified only within the defining task

Invalid statement. This variable belongs to otherTask. Cannot be modified here

Variable ScopeVA

RIA

BLE

S

Page 28: RobotC – A Tutorial I

Mathematical ExpressionsM

ATH

EXP

RES

SIO

NS

Multiplication: *int a = 3 * 4;

Division: /float b = 12.0 / 7.0;

Addition: +

Subtraction: -

Precedence (order-of-operations):int c = (4 * 3 + 12 / 6);

What is c? (12 + 2) = 14

int d = (4 * (3 + 12) / 6);

What is d? (4 * 15 / 6) = 10

Others: % (modulo or remainder)pow()log()exp()sin()cos()tan()

Page 29: RobotC – A Tutorial I

Boolean LogicB

OO

LEA

N L

OG

ICCertain operators are used to compare two variables and result in a true/false value. These are Boolean comparator operators

EQUALITY: ( var == value/var2 ) - Is the variable equal to value or another variable

results in true if the two are equal eg: (a == 20) or (a == b)

INEQUALITY: ( var != value/var2 ) - Is the variable NOT equal to value or another variable

results in true if the two are NOT equal eg: (a != 20) or (a != b)

GREATER/LESS: ( var > value/var2 ), ( var < value/var2 ) – Is the variable greater than or less than the value or another variable

results in true if the first value is greater (first case) than or less than eg: (a > 20) or (a <= b)

Page 30: RobotC – A Tutorial I

Boolean LogicB

OO

LEA

N L

OG

ICComputers don’t understand the concept of ‘maybe’ like we do. For them, its either ‘true’ or ‘false’

eg: Are you enjoying this presentation? True/False Is your hovercraft going to fly? True/False

Certain operators have results which are true or false

OR: (condition1) || (condition2) - Is condition 1 true OR condition 2 true results in true if either of the two conditions is true eg: (a > 20) || (b <= 10)

AND: (condition1) && (condition2) - Is condition 1 true AND condition 2 true results in true if both of the two conditions are true eg: (a > 20) && (b <= 10)

NOT: ! (condition1) – NOT the same result as condition 1 results in true if the condition is false, and vice versa eg: !(a > 20)

Page 31: RobotC – A Tutorial I

Programming FlowThe general flow of execution of a program is on a sequential basis from the top to the bottom

1

2

3

4

5

6

7

8

9

task main ()

{

motor[motorA] = 50;

motor[motorB] = 50;

wait1Msec(2000);

motor[motorA] = -50;

motor[motorB] = -50;

wait1Msec(2000);

}The regular flow can however be modified to Run some statements in parallel or

Exclude some statements from execution (conditioned)

by the use of CONTROL STRUCTURES CO

NTR

OL

STR

UC

TUR

ES

First motor A is started at 50% powerThen motorB is started at 50% power

Then the program waits for 2000 msec

Then the motorA is reversed and run at power level 50

…an so on, the program continues

Page 32: RobotC – A Tutorial I

Control StructuresControl Structures can be used to alter the flow of execution of the program

Each control structure has a set of statements, delimited by the { } punctuation symbols.

Within each control structure, the statements are run sequentially

CO

NTR

OL

STR

UC

TUR

ES

Page 33: RobotC – A Tutorial I

Task A Task allows execution of several set of statements in parallel.

In general, tasks are used to run a constant sequence of commands which may not affect the functional logic of the program but just act as data-feeders

RobotC supports the definition of a maximum of 10 tasks

Though tasks are run in parallel, running a large number of tasks tends to slowdown the overall performance of the system

Why?? Because of various factors like scheduling overhead and processing overhead.C

ON

TRO

L ST

RU

CTU

RES

Page 34: RobotC – A Tutorial I

Task ExampleC

ON

TRO

L ST

RU

CTU

RES

Get Data from the Gyro sensor

Start

The following is an example, where a task may be useful. Consider the case where a sensor provides data about the rotation of the RoboCar.

Make corrective turn

Start

Go Straight

Is the cardeviating from desired

direction?Yes No

Use of data fromtask in decisionmaking

A task can be designed to monitor the angle of turn and update a variable which can be used in the main logic

Update Variable: angleOfTurn

Page 35: RobotC – A Tutorial I

TaskThe basic syntax of a task may be written as follows

CO

NTR

OL

STR

UC

TUR

ES

1

2

3

4

task taskName

{

set of statements to run

}

Task Punctuation

May have other control structures (not other task definitions though)Program execution always begins at

the main task. Hence it is mandatory to have that

Other tasks may be started or stopped from within the main task by usingStartTask(task_name);StopTask(task_name); A task must be defined before it

is started or stopped => Tasks must be defined before main task

Page 36: RobotC – A Tutorial I

FunctionsFunctions are used primarily for reusing frequently occurring chunks of code (much like a task)

There are some major differences between a task and a function

CO

NTR

OL

STR

UC

TUR

ES

Task Function

Runs in parallel with the invoking code

Runs sequentially with the invoking code

Cannot accept arguments Can accept arguments

Cannot be run again without stopping previous instance

Can be run as many times as needed without caring about previous instance

Page 37: RobotC – A Tutorial I

Functions - TerminologyIn functions terminology,

Return parameter – This is the value that is computed inside the function and passed to the calling code.

i.e. a value that gets assigned to some variable inside the calling code

Function argument – This is the value which needs to get into the function but resides with the calling code.

So it is passed to the function through a dummy variable

CO

NTR

OL

STR

UC

TUR

ES

Page 38: RobotC – A Tutorial I

FunctionsThe basic syntax of a function may be written as follows

CO

NTR

OL

STR

UC

TUR

ES

1

2

3

4

5

returnType funcName(dataType arg)

{

set of statements to run

return varName

}

The datatype of the value that the function is going to return

Datatype of the argument that the function accepts

Variable name corresponding to the return argument

Variable name corresponding to the argument being passed

Function name

Page 39: RobotC – A Tutorial I

FunctionsC

ON

TRO

L ST

RU

CTU

RES

Names needn’t be the same

Names needn’t be the same

Same name

The function argument and what gets used inside must have same name

This function would be used in a program that needs to square numbers several times.

Page 40: RobotC – A Tutorial I

If - ElseAn if-else Statement is one way to make a decisionProgram will check the (condition) and then execute one of two pieces of code, depending on whether the (condition) is true or false.

CO

NTR

OL

STR

UC

TUR

ES

During each execution, only one of the if-else conditional statements will run i.e. Among all the set of statements, only one set will be run

1

2

3

4

5

if (conditon) {

set of statements to run

} else {

set of statements to run

}

Variable whose value is to be used for decision

Set of statements to run if the condition evaluates to true, i.e. Boolean value 1

Set of statements to run if the condition evaluates to false, i.e. Boolean value 0

Page 41: RobotC – A Tutorial I

If-Else ExampleC

ON

TRO

L ST

RU

CTU

RES

Condition to be checked. If the value of the light sensor is greater than 50 or less than 50

If true, i.e. the value is greater than 50, go forward. Run these statements

If false, i.e. the value is less than 50, go backward. Run these statements

Page 42: RobotC – A Tutorial I

Switch - CaseThe switch-case command is a decision-making statement which chooses commands to run from a list of separate “cases”.

CO

NTR

OL

STR

UC

TUR

ES

1

2

3

4

5

6

7

8

9

10

switch (value) {

case value1:

set of statements to run

break;

case value2:

set of statements to run

break;

default:

set of default statements

}

Variable whose value is to be used for decisionIf the value of the variable is value1, then

Run the following statements

Break – once done running these statements, come out of this structure

Default – if none of the above matches, then run these

During each execution, only one of the switch-case values is selected executed. i.e. Among all the set of statements, only one set will be run

Page 43: RobotC – A Tutorial I

Switch – Case ExampleC

ON

TRO

L ST

RU

CTU

RES

The variable myVar is used to decide between various cases

If the value of myVar is 1, run motor A forward with power 50

If the value of myVar is 2, run motor A backward with power 50

Otherwise, run motor A forward at full power

Page 44: RobotC – A Tutorial I

If-Else/Switch-CaseThese seem similar and may be used interchangeably in many cases (but not always)

CO

NTR

OL

STR

UC

TUR

ES

The if condition can always be used to replace the switch condition (because number of switch conditions is always finite and generally small), but not vice-versa.

Page 45: RobotC – A Tutorial I

If-Else/Switch-Case

Can you think of an example where the if statement may not be replaced by a switch statement?

CO

NTR

OL

STR

UC

TUR

ES

Try writing a switch case for a simple condition

if ( tempVar > 50 ) {

// Do action 1

} else {

// Do action 2

}

Page 46: RobotC – A Tutorial I

WhileA while loop is a structure which allows a portion of code to be run over and over, as long as a certain condition remains true.

CO

NTR

OL

STR

UC

TUR

ES

1

2

3

4

while (condition) {

set of statements to run

set of statements to run

}

Condition which is checked. As long as the condition is true, the loop is repeated.

The condition must result in a Boolean (1 or 0) value

Set of statements which are repeated again and again

Page 47: RobotC – A Tutorial I

While ExampleC

ON

TRO

L ST

RU

CTU

RESCondition to be checked.

While the value of the global variable myFlag is not equal to false/0, continually run the statements

Statements to be run again and again

Every while loop must have some condition that updates the test condition in a way such that at some point of time, the test condition becomes unsatisfied.

Otherwise, the loop will run forever

(myFlag == true)

myFlag = (SensorValue(x) > THRESH);

bool myFlag = true;

Page 48: RobotC – A Tutorial I

ForA for loop is a structure which allows a portion of code to be run over and over, as long as a certain condition remains true.

It is quite similar to a while loop. The primary difference is that it has an initialization and update section within the loop definition

CO

NTR

OL

STR

UC

TUR

ES

1

2

3

4

for (init; condition; increment) {

set of statements to run

set of statements to run

}

Condition which is checked. As long as the condition is true, the loop is repeated.

Set of statements which are repeated again and again

Initialization of the variable, done at the beginning of the loop

Updating the variable. Done after each iteration

Page 49: RobotC – A Tutorial I

For ExampleC

ON

TRO

L ST

RU

CTU

RES

Condition to be checked.

While the value of the variable ‘i’ is less than or equal to 10, continue running the loop

Statements to be run again and again

Updating ‘i’ by 1 after every iteration

Initializing ‘i’ equal to 0

Page 50: RobotC – A Tutorial I

SummarySE

CTI

ON

SU

MM

AR

Y

Till now you have learned The basic syntax of programming Basics about variables and usage Basic Boolean algebra for programming applications The various control structures

ALL of these concepts (EXCEPT Tasks) are native C concepts which can be applied in all C based languages

Page 51: RobotC – A Tutorial I

Questions???Q

UES

TIO

NS

Page 52: RobotC – A Tutorial I

Exercise 0• Open up the sample code database• Try running something

(good example: path following)• Modify it• See if your modifications worked

Page 53: RobotC – A Tutorial I

Exercise 1 – 5 Minutes• In the following code, find all of the errors.

task main(Check Light Sensor Value){ Int light ==0; while(true) ( if(li ght < 45) { nxtDisplayTextLine(3, “Too Low”) //Display “Too Low” } else(light > 50) { nxtDisplayTextLine(3, “Too High”); /Display “Too High” } )}

123 4 5 6 7 8 9 10 11 1213 1415

Page 54: RobotC – A Tutorial I

Exercise 1 – 5 Minutes• Correct Code:

task main(){ int light =0; while(true) { if(light < 45) { nxtDisplayTextLine(3, “Too Low”); //Display “Too Low” } else { nxtDisplayTextLine(3, “Too High”); //Display “Too High” } }}

123 4 5 6 7 8 9 10 11 1213 1415

Page 55: RobotC – A Tutorial I

BACKUP SLIDESB

AC

KU

P SL

IDES

Page 56: RobotC – A Tutorial I

Firmware – What is it?It is the Operating System for your robotIt is the Operating System for your robot

Think of what Microsoft Windows does to your computer other than make it

hang!!

It is an interface between the hardware (the robot) and the software (code that you write)

SETU

P

RobotCProgram

CompiledCode

Robot Runs

Compiler Firmware

Page 57: RobotC – A Tutorial I

Firmware – How to install?SE

TUP

In case the NXT has some firmware that is not compatible with RobotC or there is an upgrade available, the firmware on the brick would have to be updated. It can be done through a few simple steps

Click on the Robot tab on the menu bar and select the Download Firmware option

Before starting , make sure that your NXT is turned on

and has enough battery

Page 58: RobotC – A Tutorial I

Firmware – How to install?SE

TUP

Clicking the option will open a dialog box. Once the NXT is found, the F/W Download button will become active. Click the Download button

Location of the NXT found

Clears anything present in the NXT buffer for loading

Good idea to do before firmware update

Log of what is happening

Page 59: RobotC – A Tutorial I

Firmware – How to install?SE

TUP

Select the latest version of the firmware available and click Open. Before this step, ensure that the battery of the NXT is at least 50% charged

Latest firmware file

Page 60: RobotC – A Tutorial I

Firmware – How to install?SE

TUP

Firmware should install successfully. Then close the firmware window

Firmware successfully downloaded

Message Log

Page 61: RobotC – A Tutorial I

Syntax – 5 minute activityPR

OG

RA

MM

ING

RU

LES

Take 5 minutes. Open any of the demo programs and do the following activities

1. Save the program under a different name File -> Save As -> <YourName>.cIf this step is not done, then you may accidently overwrite the original code while experimenting. Caution: Every time the code is compiled, it is automatically saved.

2. Try to change the code and intentionally making some of those syntax errors we had talked about. You can try to - Remove semicolons - Introduce spaces between keywords - Try capitalization of certain words - Try changing keywords

3. Now try compiling the program to see the kind of error messages you get. To better identify, try introducing the errors one at a time. To Compile, simply hit F7

Page 62: RobotC – A Tutorial I

For Example - ExerciseC

ON

TRO

L ST

RU

CTU

RES

If the code on the previous slide is run, How many times do you think the car will move?

10??? WRONG

The correct answer is 11 times

Try counting the numbers from 0 to 10, both inclusive

Page 63: RobotC – A Tutorial I

While/ForC

ON

TRO

L ST

RU

CTU

RES

The ‘for’ is being used as a while by dropping the initialization and update logic from the loop declaration

A while and a for statement can always be substituted for each other.