07 RobotBASIC
07 RobotBASIC
Fall 2013
Programming is FUN!
in addition to being a software package user, engineers
and ETs can often benefit from being able to program
computers for particular tasks
solving special / newly discovered problems
simplify your job function / responsibilities
promotions!
to do so, we need to learn a programming language
rules, reserved words, syntax
MANY computer programming languages / environments
exist
general purpose / special purpose
mathematical/scientific, database/e-commerce, process control,
artificial intelligence
BASIC, C, C++, J ava, COBOL, Matlab, LabVIEW, PLCs
2
BASIC
Beginners All-purpose Symbolic Instruction Code
very easy to learn & use
carefree formatting, data typing, syntax
created in 1964 at Dartmouth College
a family of general-purpose, high-level programming
languages
over 300 dialects (http://en.wikipedia.org/wiki/List_of_BASIC_dialects)
has evolved through many incarnations over the years:
Tiny-BASIC, Apple BASIC, Micro-Soft BASIC, IBM QuickBASIC,
Microsoft Visual Basic, VB.NET
and now:
Parallax PBASIC, RobotBASIC
3
LANGUAGE SUMMARY
4
BASIC Programs
BASIC is a line-oriented language
Program = series of statements
Statement
Statement
Statement
statements may contain various language elements
5
Language Elements
numbers
variables
operators
expressions
constants
strings
functions
6
covered on the following slides
Numbers
numeric values for computation, etc
four types in RobotBASIC:
: whole numbers
between -2,147,483,648 +2,147,483,647 (32 bit representation)
include a decimal point
2.23E-308 1.79E+308
(32 bit) integers: start with 0%
ex: n=0%110101 // same as n=53
(base 16) integers: start with 0x
ex: n=0x1F // same as n=31
7
number of unique binary patterns with n bits = 2
n
Variables
are programmer-defined names of storage locations
variable naming rules
must start with a letter, can then have any combination of letters &
numbers; are case sensitive
cannot be same as a command, function name, constant name or
label
RobotBASIC allows variables up to 255 characters
RobotBASIC variables are typeless and do not require
declaration before use
8
goals = 2 / / goal s i s t he var i abl e name
Operators
quite similar to calculator
operators
including precedence rules
RobotBASIC operator
summary (in precedence
order) shown to right
note: some operators are
RobotBASIC-specific
see Helpfile for examples
9
( ) overrides other precedence rules
- unary negation
^ exponentiation
*, / multiply, divide
# modulus (remainder)
% numeric percentage
+, - add, subtract
$ substring test
<, <=, >=, > less, less or equal, greater or equal, greater
=, == equality
<>, ><, != inequality
&&, ||, @@, ! logical AND, OR, XOR, NOT
&, |, @, ~ bit-wise AND, OR, XOR, NOT
>>, << bit shift left, right
bRotL, bRotR bit rotate left, right
++, -- increment once, decrement once
+=, -=, *=, /= add / sub / multiply / divide assign
Expressions
a formula comprised of numbers, variables, strings,
function calls, operators, and other expressions that yields
a result
used in variable assignments as well as parameters to
commands and function calls
notice precedence rules in that last statement
10
I nput " Radi us: ", radius
ci r cumf er ence = 2*pi()*radius
pr i nt " Ci r cumf er ence = " , circumference
pr i nt " Ar ea = " , pi() * radius^2
function call
numeric constant
variable reference
operators operators
Constants
RobotBASIC provides many predefined names for certain
numeric values
always more meaningful compared to using number
instead of:
also useful in measure conversions:
cc = conversion constant
11
Ci r cl e 10, 10, 30, 30, Red
Ci r cl e 10, 10, 30, 30, 4
pr i nt Conver t ( 212, cc_DFtoDC)
Strings
textual content, arrays of characters
delimited with quotation marks
can apply certain operators to strings
+ performs string concatenation
$ performs substring testing
12
msg = " al i ve! "
Pr i nt " Hel l o Wor l d, "
i f " l i ve" $ msg t hen
Pr i nt " I m" + msg + " ! "
Functions
use to call a built-in or programmer-defined subprogram
unit that returns a result
can be used in expressions
like pi() in previous example
format:
FunctionName(parameter1,parameter2)
parameters separated by commas, may be optional
note use of parentheses; Command statements do not use them
13
Pr i nt " l og( 1000) = " , log(1000)
RobotBASIC Functions
there are MANY functions built in to RobotBASIC
categories:
trig, logarithmic, exponential, coordinate, financial
string manipulation
scaling, weight & measure, number<->string
& I/O
, , chrono/calendar, system information
refer to Helpfile for details
14
Statement Types
Assignment: assign a value to a variable
Command: built-in features that perform various tasks
Flow Control: control the sequence of program execution
Comment: provides documentation
not actually statements
Label: provides a name for a program location
15
Comments
Line comments
from // or to end of line
Block comments
everything between /* and */
16
/ / t hi s i s a l i ne comment
' so i s t hi s
count = 0 ' i ni t i al i ze count t o 0
/ *************************
t hi s i s an exampl e
of a bl ock comment
**************************/
Assignment Statements
assigns value to a variable or array element
value can be a constant or result of an expression
formats:
Var = expression
Var[] = expression
[ ] denotes index to an array variable
17
r adi us = 3. 5
di amet er = 2*r adi us
Speed[ 5] = 12
Command Statements
perform built-in tasks
input, output, drawing, robot actions, etc.
format:
CommandName parameter1,parameter2
commands are not case sensitive
parameters separated by commas, may be optional
18
Circle 20, 20, 40, 40, r ed r adi us=10, cent er =30, 30
Print " Ci r cl e i s dr awn"
End
Labels
is a marker (think bookmark) for a particular location in the program
use by flow control statements to transfer execution to other than the
next line
includes a colon : where defined
RobotBASIC: can be numeric or alphanumeric style
19
I nput " How ol d ar e you? ", age
i f age<0 t hen goto Alien
Pr i nt " you must be human"
end
Alien:
pr i nt " you must be al i en"
end
Flow Control Statements
control flow of program execution
unconditional
conditional tests & program branching
/ / /
iteration / repetition
/
/
/
/
invoke subroutines / subprograms
/
20
Conditional: IF
evaluates a numeric expression
and conditionally executes
statement(s) based on result
2 formats
:
IF expressionN THEN statement
IF expressionN
statement
{ELSEIF expressionN}
statement
{ELSE}
statement
ENDIF
21
a=5
If ( a- 3) >0 Then Pr i nt " ok"
' check cof f ee t emper at ur e
t = t empsensor ( )
If t >190
Pr i nt "t oo hi gh"
ElseIf t <140
Pr i nt "t oo l ow"
Else
Pr i nt "ok"
EndIf
{}indicates optional content
Iteration: FOR
used when number of loops
needed is already known
format:
FOR var=expr1N TO expr2N
statement
NEXT
may include optional "STEP"
clause
expression2 is generally >
expression1; however, can
also go in decreasing direction
22
For i =1 To 5
Pr i nt "i =", I
Next
For i =5 To 20 Step 5
Pr i nt i
Next
For i =100 To 0 Step - 1
Pr i nt i , " bot t l es of beer "
Next
' act ual l y, t hi s STEP i s opt i onal
Iteration: REPEAT
used to repeat a loop until a
condition is met
format:
REPEAT
statement
UNTIL expressionN
statement(s) execute at least
once
23
Pr i nt " guessi ng game"
n=Random( 100)
Repeat
I nput "guess?" , g
I f g<n
pr i nt " t oo l ow"
El seI f g>n
pr i nt " t oo hi gh"
El se
pr i nt " t hat ' s i t ! "
EndI f
Until g=n
Iteration: WHILE
used to repeat a loop as long as
a condition is true
format:
WHILE expressionN
statement
WEND
statement(s) may execute zero
times!
24
' advance r obot car ef ul l y
' get i ni t i al di st ance
d=sensor _di st ance( )
While d > 5
r For war d 5
' get new r eadi ng
d=sensor _di st ance( )
Wend
Iteration: Alternative Loop Control
used to handle special circumstances
BREAK:
abandons enclosing loop and continues with statement following
loop
CONTINUE:
forces next iteration of enclosing loop
25
Subroutines: Gosub-Return
used to organize a code
sequence into a module,
typically reusable
formats:
GOSUB label
GOSUB expressionN
statement
code at label is executed until a
RETURN is reached
26
I nput " ent er N: ", n
Gosub Summat i on
Pr i nt " summat i on=" , t ot al
End
Summat i on:
t ot al =0
For i =1 t o n
t ot al = t ot al + i
Next
Return
Subroutines: Call-Return
a more advanced subroutine
mechanism that supports
parameters and local variables
parameters are passed by value
or by reference
format:
CALL label{(parameter list)}
code at label is executed until a
RETURN is reached
27
I nput " ent er N: ", n
Call Summat i on( n, r esul t )
Pr i nt " summat i on=" , r esul t
End
Sub Summat i on( x, &t ot al )
t ot al =0
For i =1 t o x
t ot al = t ot al + i
Next
Return
ROBOT SIMULATOR
28
Robot Simulator
RobotBASIC includes a neat simulated robot environment
with a collection of associated commands and functions
some features:
obstacle detection and abort
robot sensors to detect & avoid obstacles
full color support
robot "tail" that can draw (if "down")
invisible colors are not detected as obstacles
simulated robot battery and charge state
heading and position tracking via simulated compass & "GPS"
simulated "slip" factor for motions
29
Robot Simulator Commands Summary
creates & locates robot
sets colors that will not be considered
obstacles
defines floor color (default is WHITE)
moves forward/backward some number of
pixels
rotates robot CW (+) or CCW (-)
sets robot's heading (0-359 degrees)
sets a robot "slowdown" factor
sets robot's pen UP or DOWN
sets a motor slip factor
30
Heading Details
and are based on directional compass
measure
as opposed to mathematical angle measures
31
0
180
90 270
90
270
0 180
135
135
Robot Simulator Functions Summary
distance ahead to any obstacle
distance to obstacle of particular color
obstacle detection using bumper switches
obstacle detection using infrared sensors
get first color seen directly ahead
reads a down-facing sensor
looks down for a particular color
gets robot's current compass heading
gets robot's current X screen position
gets robot's current Y screen position
32
rBumper() details
the robot has 4 bump sensors (switches)
front, rear, left, right
each switch has an assigned
bit position in the return value
(bottom 4 bits):
each bit is 1 if bump sensor is active (object within 2 pixels) or 0 if not
ex: return value of 4 (0100
2
) means front bumper is active
use bitwise Boolean operators to evaluate result
ex:
33
left front right rear
bit: 3 2 1 0
I f ( rBumper()&4) = 0 t hen ' f r ont bumper i nact i ve
I f ( rBumper()&4) ! = 0 t hen ' f r ont bumper act i ve
rFeel() details
the robot has 5 infrared sensors
center, 45, 90
each sensor has an assigned
bit position in the return value
(bottom 5 bits):
each bit is 1 if object detected or 0 if not
range distance is same as robot's radius
ex: return value of 40 (11000
2
) means objects are towards the left of robot
use bitwise Boolean operators to evaluate result
as with rBumper()
34
-45 0 +45 +90
bit: 4 3 2 1 0
-90
+90 -90
0
rGround() details
the robot has 3 down-facing sensors
center, 10
each sensor has an assigned sensor number, one of which must be
passed to rGround as an argument
3=10 left, 2=center, 1=10 right
rGround() returns color seen directly under specified sensor
and does not ignore any colors, even if invisible
ex: move forward until robot is over something yellow
35
+10 -10
0
Repeat
r For war d 1
Unt i l rGround(2)= YELLOW