# Lab 3: Building Robot Brains

## Objectives

• Write and implement programs to do simple calculations
• Calibrate your Robot to move straight
• Use For Loops to do tasks that require repetition

## Writing programs to do calculations

Writing programs to do computations is very similar to writing programs that control your robot. They both require the same basic structure. The only difference is that you will use the Myro library to write all your robot programs. You can set your robot aside for this exercise.

### A Calculating Program: Salary Calculator

In this section you will use many of the concepts you learned in the first lab such as defining variables, writing functions and creating modules, to write programs that perform simple calculations. Here is a simple problem:

Problem: If you work 10 hours per day, 6 days per week and you earn \$30 per hour. How much would you earn in a month?

In order to answer the question, all you have to do is multiply 6 by 10 by 30 by 4 to get 7200 dollars. You can also use Python to do this calculation by typing the following in Calico:

```>>> 6*10*30*4
```

You should see the following when you do so:

```>>> 6*10*30*4
7200
```

You can also save your program in a module as follows:

```# File: salary.py
# Name: Telia Golden
# Description: A program to calculate a worker's monthly salary

def calcSalary():
hourlyRate = 30
daysWorked = 6
hoursWorked = 10
weeklySalary = 30 * 6 * 10
monthlySalary = 4 * weeklySalary
print("Monthly Salary is: ", monthlySalary)

calcSalary()
```

### Using Input

The program we wrote above uses specific values for the hourly rate, the number of days worked and the hours worked each day. As such, this program solves only one specific problem for the values stated above. But suppose we wanted to calculate the monthly salary for a different employer who works earns a different hourly rate and works more or less days per week. We can make this program more general and thus more useful in a variety of cases by using the input function in python. Most computer programs take some form of input, do some computation with that input, and then produce some output. Python has a simple input command that we can use to generalize our program. We can rewrite the program above as follows:

```# File: salary.py
# Name: Telia Golden
# Description: A program to calculate a worker's monthly salary

def calcSalary():
# Print a description of the program

print("This program computes the monthly salary of an individual")
print("Please enter the values requested below.")

# Input the values
hourlyRate = float(input("Enter your hourly wage: "))
daysWorked = int(input("Enter the number of days you work per week: "))
hoursWorked = float(input("Enter the number of hours you work per day: "))

# Compute Results
weeklySalary = hourlyRate * daysWorked * hoursWorked
monthlySalary = 4 * weeklySalary

# Output Results
print("Monthly Salary is: ", monthlySalary)

calcSalary()
```

The comments we've used help to improve the overall readability of the program. The syntax of the input function is shown below:

```<string variable name> = input(<some prompt string>)
<integer variable name> = int(input(<some prompt string>))
<float variable name> = float(input(<some prompt string>))
```

The input function takes a string as a parameter and the value it returns is the value of the expression that will be entered by the user. That is, when executed, the computer will print out the prompt and wait for the user to enter a Python expression. The expression is then evaluated by Python and the resulting value is returned by the input function. That value is then assigned to the variable <variable name>. Observe the use of the input function in the program above. With this modification, we now have a more general program which can be run over and over again. Once you've run the module once, you can re-run the program by typing calcSalary() at the command prompt in the python shell.

## Building Brains

Each Scribbler Robot Kit contains the following items:

1. The Scribbler Robot
2. The Fluke Board
3. The Bluetooth Dongle (This is the USB key stuck on top of your robot)
6. 4 color permanent marker pens
7. A carrying case for your kit

The main components of the kit are shown below:

Make sure that all of these parts are present in your kit. If anything is missing, or you are having trouble identifying something, please call your instructor to help you. If your fluke is detached from your robot, attach it now using the connector in the image above.

Your Fluke dongle has a barcode with a number on it (a 6-digit number). You will need this number to create the connection to the computer. Write this number on your notebook. Also, using a Sharpie, write it down on the inside cover of your carry case, as well as on the underside of the robot itself, and on the Bluetooth dongle. This will also ensure that all your parts are accounted for. In case they get misplaced, we will be able to trace them back to you. We will also note this number in our records. As an example, we will use the number: 125802.

For details about how to connect to your robot, please see the setup instructions and refer to your operating system. Specifically, for the Bryn Mawr College lab computers, see Bluetooth Setup for Calico Myro on Windows XP

**Tip:** Make sure your game pad is plugged into a USB port before starting Calico,

Once your Bluetooth device is configured, open the Calico shell. If you don't do this now, then when you try to do it later on, you will need to insert your game pad into a port later on and restart your python shell.

To start Calico:
Double click the “StartCalico” icon on your desktop.

The next step is to use Myro to communicate with your robot. To import all the functions from the Myro library, type the following command at the prompt:

```>>> from Myro import *
```

To connect to your robot, (Note: You will need to enter the passkey (1234) again to fully connect to your robot) type the following :

```>>> init()
```

You could also type something like, where "com5" is a string that indicates your COM port:

```>>> init("com5")
```

The init() function tries to establish communication between your computer and your robot. If this is successful, the robot responds with the Hello... line shown above. In the example above, the robot's name is Scribby. You can change this name to whatever you prefer. We will do this next.

To name your robot SuperBot, type the following command:

```>>> setName("SuperBot")
```

To give your robot a different name, replace the word SuperBot in the setName function above. To ask the robot its name, type the following:

```>>> getName()
```

By using the setName command, you have permanently changed the name of your robot. It will report this name every time you connect to it using the initialize command:

```>>> init("com5")
Waking robot from sleep...
Hello, I'm SuperBot!
>>>
```

To make the robot beep, enter the following command at the prompt:

```>>> beep(2, 700)
```

The command above tells your robot to make a beeping sound at 700 Hertz for 2 seconds. Try a combination of sounds. You can play two tones at once:

```>>> beep(1, 400, 800)
```

This will play two tones, one at 400 Hz and the other at 800 Hz for 1 second.

You can define your own functions and place different beep commands in this function. An example of this giving below:

```>>> def mySong():
beep(1,500)
beep(2,880)
wait(1)
beep(4,680)
beep(3,800)
```

In this exercise, you will control your robot's movements using the game pad device in your kit. Your game pad should be plugged into a USB port (following the tip I gave you earlier). If you haven't done so yet then locate an available USB port on your computer and insert your game pad controller into this port. You will need to restart the shell to use the gamepad() function. The annotated image below shows a game pad similar to the one you will be using.

To use the game pad, type the following at the prompt:

```gamepad()
```

You should see the following options when you do this:

```        Pad   Action
------   -------
Left/Right   turnLeft() and turnRight()
Up/Down   forward() and backward()

Button   Action
------   -------
1   stop()
2   takePicture()
3   beep(.25, 523)
4   beep(.25, 587)
5   beep(.25, 659)
6   speak('Hello. My name is Dribbler.')
7   speak('Ouch! I'm a sensitive robot.')
8   speak('I'm hungry. Do you have any batteries?')

Gamepad is now running... Press button 1 to stop.
```

Use the buttons on your game pad to move your robot around as well as to explore additional features of your robot (e.g. taking a picture, beeping or speaking).

## Using Different Commands to Move Your Robot

In this section, you will explore other commands to control your robot's movements. The following commands allow your robot to move forward, backward, to the left, to the right, to spin and to stop all movement:

• forward(amount, seconds)
• backward(amount, seconds)
• turnLeft(amount, seconds)
• turnRight(amount, seconds)
• rotate(amount, seconds)
• stop()

You can, for example, type the following:

```>>> forward(0.5, 2)

>>> turnLeft(.6, 1)
```

You can find these and all other robot commands in the Myro Reference Manual

### Brains

Robots and computers are intricately connected. So far, you have been writing programs in Python to control your robot through the computer. Therefore, by writing robot programs you are also learning how to program computers. Also, by programming your robot, you are building its brain.

Every program you write to control your robot, usually begins with the following lines:

```from Myro import *
init()
```

However, that will ask for you to enter your COM port each time (which you would enter without the quotes, no spaces, such as COM5 on Windows).

If you wanted to hardcode the COM port, you could do it like so:

```from Myro import *
init("com5")
```

The first line, as you know, imports the Myro library and all its functions while the second line establishes a connection between the computer and your robot. After this, you usually define functions which contain several commands that tell your robot to carry out specific tasks. The module below contains a song and dance routine.

```# File: dance.py
# Author: Jessica Fields
# Description: A song and dance routine

# First import myro and connect to the robot

from Myro import *
init()

# Define the new functions

def botDance(amount, seconds, speed, waitTime):
forward(speed)
wait(waitTime)
backward(speed)
wait(waitTime)
turnLeft(amount, seconds)
turnRight(amount, seconds)
stop()

def botSong(waitTime):
beep(3, 800)
wait(waitTime)
beep(2, 550)

# The main routine
def main():
speak("Lets dance")
botSong(1)
botDance(0.5, 2, 0.5, 1)
speak("I am the greatest entertainer alive")

main()

```

The botSong and botDance use several functions from the Myro library namely: forward, wait, backward, turnLeft, turnRight and beep. We can then combine these functions and create even more complex tasks such as the routine in the main function. Run this module and test it on your robot. You can also modify the functions as you please. You can run this module as you've been doing so far, by selecting Run then the Run Module option or equivalently F5, or you can type the following at the command prompt in Python:

```from dance import *
```

The statement above tells the computer to import all the functions from the dance module so that you can use them without without redefining them at the prompt in the Python shell.

## Doing Repetition in Python

### An Introduction to For and While Loops

Now suppose you wanted to repeat your dance routine several times. One way you could do this is by using a for loop. Try the following:

```>>> for i in range(3):
botDance()
```

When you executed this command, your robot performed its dance three (3) times. The for loop is a statement you can use to perform a task a fixed number of times. The syntax of the for loop is:

```for <variable> in <sequence>:
<do something>
<do something>
...
```

The first line, for <variable> in <sequence>, specifies the number of times a task should be repeated. When the computer executes a for-statement, the <variable> which is known as a loop index variable is assigned successive values in the <sequence>. After each assignment, the commands in the loop body are executed. For example, look at the botDance example above and notice that we have used the function range(3) to specify the sequence. Try typing the following command at the prompt:

```>>> range(3)
```

You should see the following:

```>>> range(3)
[0, 1, 2]
```

range(3) is a sequence (a list) of 3 numbers 0..2. Therefore, the variable i in the loop:

```>>> for i in range(3):
botDance()
```

will be assigned values 0 through 3 and every time it is assigned a new value, the botDance() function will be executed. Let us test this on the robot. Modify the module above to include a for loop in the main() function:

```# File: dance.py
# Author: Jessica Fields
# Description: A song and dance routine

# First import myro and connect to the robot

from Myro import *
init()

# Define the new functions

def botDance(amount, seconds, speed, waitTime):
forward(speed)
wait(waitTime)
backward(speed)
wait(waitTime)
turnLeft(amount, seconds)
turnRight(amount, seconds)
stop()

def botSong(waitTime):
beep(3, 800)
wait(waitTime)
beep(2, 550)

# The main routine
def main():
speak("Lets sing and dance a lot")
for routine in range(3):
botSong(1)
botDance(0.5, 2, 0.5, 1)
speak("I am the greatest entertainer alive")

main()

```

Notice that we have replaced the index i with a more meaningful variable, routine, to specify the loop index variable. When you run this module, your robot should perform the routine three times. Another useful loop is the while loop. You can use the following if you want robot to execute a particular task forever:

```while True:
<do something>
<do something>
...
```

To stop the computer and your robot you can hit CONTROL-C by pressing the Control and the c-key simultaneously.

### Using for Loops to do Tasks that are Repetitive in nature

For loops are particularly useful when you want to do tasks that inherently require taking repeated steps. Suppose you wanted your robot to draw a square for example. Then the steps to do this task, the algorithm (in comments) would look something like this:

```def drawSquare():
forward(0.5, 2) #Move forward in a straight line
turnLeft(0.5, 2) #Turn 90 degrees left
forward(0.5, 2) #Move forward in a straight line
turnLeft(0.5, 2) #Turn 90 degrees left
forward(0.5, 2) #Move forward in a straight line
turnLeft(0.5, 2) #Turn 90 degrees left
forward(0.5, 2) #Move forward in a straight line
turnLeft(0.5, 2) #Turn 90 degrees left
```

As you can see, we've repeated the same combination of steps 4 times. We can do this much more efficiently using the following for loop:

```def drawSquare():
for squareSide in range(4):
forward(0.6, 3) #Move forward in a straight line
turnLeft(0.5, 2) #Turn 90 degrees left
```

Try it yourself i.e. have your robot draw a square. You may have to adjust the values(parameters) in the forward and turnLeft functions. After you do this, create a function called drawTriangle() that makes your robot draw a triangle.

# Assignment 03

1. Drawing a Star: Draw a five point star using a for loop. Submit the program you used to draw the star, and the star drawn.

2. Dancing Robots: Create a program makes your robot dance using the knowledge of loops learned during this lab.

3. Writing Review: Write a short reflection on the lab. What was most difficult? What was the most interesting? Please include other items of interest.