Useful Commands for YOU

From IPRE Wiki
Jump to: navigation, search

Below is a list of useful Myro and Python commands, organized by the type of command. These originally appeared on the "Useful Commands for YOU" poster.


Ever wanted to see the major commands you’ll be using with Myro and Python written down in one list in one place for quick and easy reference? Here you go…

How to Use this Manual: This reference sheet has three main sections, highlighted in green: Myro, Python, and Libraries in Python. In each section there are subsections highlighted in blue, and within these are categories listed in purple. In each subsection or category, there is a list of related functions. In general these are listed from more general and simple to more specific and complex, and functions are grouped with similar functions. However, the sections / categories on robot sensors, strings, lists, and the math library are arranged alphabetically.

Each function listed has a brief description beside it. Next to the description, some functions have useful extra information and/or a corresponding chapter number for the text Learning Computing with Robots (Ed. Kumar, Deepak 2007) listed beside the function. See also the key listed on the top right of this poster (highlighted yellow) regarding function descriptions used in this reference sheet.

For more information on a command, look it up in your Intro Computer Science book or at (for more information see the blue box on the bottom right of this reference sheet).

General Key

key (Example : Description) '
init(portName) \"init\" is a function, and portName a parameter of the function (i.e. a number, string, or other data type that the function takes as input); in explanations, the parameter are referred to in italics
value terms are referred to in bold
<variable> = <expression> words referred to <in pointy brackets> represent various types of data and operations including objects, conditional statements, and commands
turnLeft(speed, seconds=None) the = specifies that the seconds parameter is optional -- if you don\'t specify an amount, seconds will automatically be set to None
getBright(*position) the * specifies that you may enter nothing, one, or multiple entries for position (entering a different number of entries may result in a different returned data type)

The Commands

Function Brief Description Extra Information Ch.
I. Myro Library (from myro import *)
A. Robot
1. Starting Up
from myro import * allows all myro commands to be used for rest of IDLE session or for remaining code 1
initialize(portName) establish connection between robot and computer within python 1
init(portName) establish connection between robot and computer within python easier to type than \"initialize\"! 1
getName() returns the name of your robot 1
setName(newName) sets the name of your robot to newName 1
2. Motion
forward(speed, seconds=None) moves forward at speed, for seconds (if indicated) speed should be in range [-1, 1] 2
backward(speed, seconds=None) moves backward at speed, for seconds (if indicated) speed should be in range [-1, 1] 2
move(translate, rotate) moves forward at translate speed and turns clockwise at rotate speed translate and rotate speeds should be in range [-1, 1] 2
motors(left, right) turns left wheel with left speed and right wheel with right speed left and right wheel speeds should be in range [-1, 1] 2
translate(speed) moves forward at speed speed should be in range [-1, 1] 2
rotate(speed) rotates clockwise at speed speed should be in range [-1, 1] 2
turnLeft(speed, seconds=None) turns left at speed, for seconds (if indicated) speed should be in range [-1, 1] 2
turnRight(speed, seconds=None) turns right at speed, for seconds (if indicated) speed should be in range [-1, 1] 2
stop() stops robot movement
wait(seconds) waits seconds before executing next command 2
joyStick(showSensors=0) provides graphical joy stick to control robot if showSensors is 1, joy stick program will display robot\'s sensor values
calibrate() provides a way to calibrate robot motors so the robot will move more straight
3. Sensors
getBattery() returns current battery power above 6.3 is OK, about 7 indicates fresh batteries 4
getBright(*position) returns Fluke light sensor values at positions given if no positions given, returns list of all values 5
getIR(*position) returns Scribbler Infrared sensor values at positions given if no positions given, returns list of all values 5
getLight(*position) returns Scribbler light sensor values at positions given if no positions given, returns list of all values 5
getLine(*position) returns Scribbler line-follower sensor values at positions given if no positions given, returns list of all values
getObstacle(*position) returns Fluke Infrared sensor values at positions given if no positions given, returns list of all values 5
getStall() returns Scribbler internal stall sensor value 4
senses() displays a window with Scribbler\'s sensor values updated each second 5
4. Camera (see also section I.C. Images)
takePicture(mode=\'color\') robot takes a picture and returns the picture object mode can be \"color\" or \"gray\" 5
show(picture) displays given picture on the screen 5
savePicture(picture, filename) saves picture to filename location make sure the filename extension is \".gif\" or \".jpg\" 5
savePicture([listOfPictures], filename) saves moving picture, created from listOfPictures, to filename filename extension must be \".gif\" 5
sendPicture(picture, photoname, password, robotname=None) sends picture with title photonameto webpage of robotname with password
5. Gamepad
getGamepad(*item) waits until item (usually either \"axis\" or \"button\") is pressed and then returns list of item info item can also be \"init\", \"name\", \"ball\", and/or \"hat\"; if no items given, returns a dictionary of all values 5
getGamepadNow(*item) immediately returns status information about item (usually either \"axis\" or \"button\") item can also be \"init\", \"name\", \"ball\", and/or \"hat\"; if no items given, returns a dictionary of all values 5
gamepad() provides interface for gameboard-robot interaction 1
6. Other Useful Functions
beep(duration, frequency1, frequency2=None) robot beeps for duration at given frequency1 can play two frequencies by assigning a value for frequency2; frequency of 261.63 hz is middle C 1
setLED(position, value) set LED at given position to value ON or OFF position is either “back” or “front”, value is \"on\", \"off\", 0, or 1
Function Brief Description Extra Information Ch.
B. User Interaction
ask(question) brings up ask dialog box where question is asked - usert types response returns as string 4
askQuestion(question, answers, title=\"Myro Question\") brings up askQuestion dialog box where question is asked - user selects button response returns as string; can specify title (a string) and possible answers (a list of strings) 4
C. Images
1. Getting Info about a Picture
getX(pixel) returns x coordinate of given pixel
getY(pixel) returns y coordinate of given pixel
getPixels(picture) returns list of pixels from picture
getColor(pixel) returns red, green, and blue values of pixel
getPixel(picture, x, y) returns pixel object at x and y coordinates of picture
getHeight(picture) returns height in pixels of picture
getWidth(picture) returns width in pixels of picture
2. Creating & Changing a Picture
makePicture(*args) creates a picture object args can either be a filename or else the columns, rows, array, and mode
pickAColor() opens a graphical interface to choose a color and then returns this color object
makeColor(red, green, blue) returns a color object from given red, green, and blue values
setColor(pixel, color) sets given pixel to color provided in the case of an image with a range of colors (e.g. grayscale images), will set pixel to nearest color
setPixel(picture, x, y, color) sets given pixel in picture to color provided
setBlue(pixel, value) sets given pixel\'s blue component to value provided
setGreen(pixel, value) sets given pixel\'s green component to value provided
setRed(pixel, value) sets given pixel\'s red component to value provided
D. Webpage
register(oldname=None) sets up registration to create webpage
setName(name) sets webpage name to name
setPassword(robotName, emailAddress, newPassword) sets newPassword as current password for webpage for given robotName and emailAddress
E. Music
makeSong(text) returns a song object from given text text should be formatted as \" \", e.g. \"e 1; f 1; g 1; a 1;\"
playSong(song, wholeNoteDuration=0.545) plays song created using makeSong() a whole note will last wholeNoteDuration seconds
F. Other
update(what) update(‘Myro’) updates Myro to most current version
timeRemaining(time) when used as the condition in a while-loop, the commands of the while-loop are executed for given time in seconds 3
currentTime() returns internal representation of current time, as integer can be used to find or restrict the time on an operation 4
randomNumber() returns a random number in the range [0, 1] 4
II. Python
A. General
#Note: for now, think of “object” or “item” to mean a piece of data of a specific data type
(for instance, an integer, floating point number, string, or list).
1. Terms and Program-Writing Basics
def (): defines a function to execute , with the given and (parameters); called function declaration functions, once defined, can be called in other parts of a code -- they make for less repetitive and more understandable coding; the code (commands) for a given function should follow the function declaration and be indented; see \"extra information\" on variable for how to name a function 2
to call a function (i.e. to start executing its commands) elsewhere in your code, type the function name followed by the arguments you want to pass it in parentheses (e.g. forward(0.5, 10) )
values numbers or strings values can stand alone or be combined with operations (e.g. +, -, *, /, % can be used with numbers) 3
variable a name that represents some value or object the first character of a variable or a function must be a letter or underscore, and the rest can be a combination of letters, digits, and underscores 3
a = b takes whatever is stored in variable b and puts it in variable a; called variable assignment in math, a = b says that a and b are inherently equal; in contrast, in computer science a = b sets a to be whatever b is
return a way to pass an in one function to another function; called a return statement functions that return values are often used in variable assignment (e.g. sum = add(num1, num2); note that once a return statement is executed, code following it is ignored
number operations can be used to combine or operate on numbers +, -, *, /, % [for numbers]
string operations
Function Brief Description Extra Information Ch.
2. Repetition and Loops
range(endNum) creates a sorted list of all integers in the range [0, endNum) there will be endNum number of things in the list, although the last element in the list is endNum - 1 3
range(startNum, endNum, step) creates a sorted list of numbers in the range [startNum, endNum) increasing by step size 3
= sets the variable to represent the value created by expression this is called variable assignment 3
for in range(): does given of times, with value increasing each time this is called a for-loop and 3
for in : does for each item of the list this is called a for-loop 3
while timeRemaining(): does for given time this is a type of while-loop 3
while : does while the condition holds, stops when the condition no longer holds this is called a while- loop 3
break breaks out of while- or for- loop early (and moves on to the next part of the code) this is a useful tool to stop while-loops and for-loops from executing comands which in normal circumstances they would execute
3. Logic
True, False Boolean (logical) values Python sets True equal to 1 and False to 0 4
<, <=, >, >=, ==, != relational operations that can be used to compare values 4
and, or, not logical expressions that can be used to combine Boolean (logical) expressions 4
4. If-Statements
if-statements a way for the computer to make a decision of what to do in different cases literally, a series of conditions with corresponding commands (which are performed when the condition is satisfied) 6
if : a general form of the if-statement, this does when is satisified, when was not satisfied but was, and does when none of the previous commands are true as many elif statements as desired can be added so long as they have a condition and commands to do when this condition is true 6
elif :
B. Help
dir(library) returns list of library’s functions
help() returns information about how a function is used (i.e. what it does, what its parameters are) to get help on classes such as string or list, type help()
C. User Interaction
raw_input(question) asks question and returns, as a string, whatever user types in response
input(question) asks question, and returns an evaluated version of whateve the user types in response evaluation means that Python figures out the data type (e.g. string, int, float, etc.) of the input
D. Opening Files
open(filename) opens filename for reading through Python
aFile.readlines() returns a list of all lines in aFile (each line is a separate item in the list) newline characters are included returns all of aFile as one string newline characters are included
urlopen(url) creates a stream connection with the url requires importing the Python module urlopen 5 reads all contents of stream as a string 5
E. Strings
s = \"a very cool string\" create a string and store it to a variable (in this case, s) and then you can use string functions to create altered versions of it
s.capitalize() returns copy of string s with its first letter capitalized
s.index(substring) returns location number of starting character of given substring of string s
s.lower() returns copy of string s with all letters lowercase
s.split(separator = \' \') by default this creates a list of all \"words\" in s (separates based on the spacebar character) more generally, returns a list of substrings of string s, separated at and deleting out the separator substring 5
s.strip(chars=None) by default this returns a copy of string without beginning and ending whitespace characters more generally, returns copy of string s with given chars deleted from its beginning and end
s.upper() returns copy of string s with all letters uppercase
Function Brief Description Extra Information Ch.
F. Lists
lyst = [] creates a new, initially empty list and assigns it to the variable lyst
#Note that “index” refers to where in the list an item is located, with the first item in the list at index 0. For example,
#in the list [‘pigs’, ‘squash’, ‘deliberation’], the item ‘pigs’ is located at index 0, ‘squash’ at index 1, and ‘deliberation’ at 2.
lyst.append(object) appends object to end of lyst
lyst.count(item) returns number of occurrences of item in lyst
lyst.index(item) returns first index (i.e. first location) of item in lyst
lyst. pop(index) removes and returns item found at index within lyst
lyst. remove(item) removes first occurrence of item from lyst
lyst. sort() sorts lyst by numerical or alphabetical order there are a few optional parameters for this function -- see documentation for more information
III. Libraries in Python
A. Random Library (from random import *)
randint(a, b) generates a random integer in the interval [a, b]
randrange(a, b) generates a random integer in the interval [a, b) 4
random() generates a random number in the interval [0, 1) 4
B. Time Library (from time import *)
clock() returns clock time analogous to Myro’s currentTime()
sleep(time) does nothing for specified time in seconds analogous to Myro’s wait(time)
C. Math Library (from math import *)
1. General Math Functions
ceil(x) returns the ceiling of x as a float (i.e. the smallest integer value greater than or equal to x) 7
exp(x) returns e**x (e to the power of x) 7
floor(x) returns the floor of x as a float (i.e. the largest integer value smaller than or equal to x) 7
log(x[, base]) Returns the logarithm of x to the given base if the base isn\'t specified, return the natural logarithm of x (i.e., the logarithm to base e). 7
log10(x) Returns the base-10 logarithm of x. 7
pow(x, y) returns x**y (x to the power of y) also available in python proper 7
sqrt(num) returns the squareroot of number num 7
2. Trigonometric Functions
acos(x) returns the arc cosine of x, in radians. 7
asin(x) returns the arc sine of x, in radians. 7
atan(x) returns the arc tangent of x, in radians. 7
cos(x) returns the cosine of x radians. 7
sin(x) returns the sine of x radians. 7
tan(x) returns the tangent of x radians. 7
degrees(x) converts angle x from radians to degrees. 7
radians(x) converts angle x from degrees to radians. 7
3. Mathematical Constants
pi a floating point approximation of the mathematical constant pi this is a variable, not a function (so don\'t add parentheses after it) 7
e a floating point approximation of the mathematical constant e this is a variable, not a function (so don\'t add parentheses after it) 7

More Information

An extensive resource for the various python libraries and the commands contained within them is located at Especially useful functions and libraries are discussed in the following sections. 1 Introduction 3 Built In Types (esp. 3.1, 3.2, 3.3, 3.11) 4.1 Strings 5.6 Array -- Efficient arrays of numeric values 6.1 Math -- Mathematical functions 6.4 Random -- Generate pseudo-random numbers

Check out the site and explore it – it’s cool & very useful!

Some definitions here have been taken in whole or in part from Python and Myro documentation strings, Learning Computing with Robots (Ed. Kumar, Deepak 2007), and