Blog

Final Project Topics

Ms. Martin : June 13, 2010 9:04 pm : 2010 Spring Creative Computing 1, 2010 Spring Exploring CS

Find inspiration in UW, CMU, Stanford research.

Artificial Intelligence
- intelligent transport systems
- swarm computing
- automatic image analysis (image search)
- automatic translation
- voice control
- natural language processing
- get ideas from MIT’s CSAIL

Human-Computer Interfaces
- brain-controlled computers
- gesture interfaces (skinput, sixth sense, Natal)

Ubiquitous Computing
- wearable computers
- “Smart grid” (sensors for electrical, power grids; HydroSense)
- RFID applications (“smart tags”, tracking)

Computing law
- laws regulating privacy
- anti-hacking laws

Large-scale computing
- quantum computing
- parallel computing (multi-core, multi-processor)

Computing Concepts
- Moore’s Law
- Agile Software Design
- Cloud Computing (Google docs, GMail, etc)
- Databases (information storage)
- Peer to peer networking (BitTorrent)
- Encryption

Human-based computation (Captcha)

Computing in the developing world

Android OS
Linux

People in computing
- Edsger Dijkstra (algorithms)
- Alan Turing (father of CS)
- Douglas Engelbart (pioneer, invented the mouse)
- Marissa Mayer (early Google employee)

Leave a response »

Final Assessment

Ms. Martin : June 8, 2010 9:14 pm : 2010 Spring Creative Computing 1

You will spend this class period completing the flickr exercise and demonstrating what you have learned over the course of the semester.  This is worth 25 project points.  You will do as many of these short programs as you can and will be graded based on completeness, how on-task you are and the appropriateness of the problems you choose to solve.  Aim to demonstrate as much knowledge as you can.

Please make sure there is a comment at the top of your program indicating your name.  Please separate each question with a comment indicating which question you are answering (Novice 1, for example).

For all sample runs below, input is underlined.  You don’t need to underline anything.

Novice

  1. Write turtle graphics code that draws an equilateral triangle.
  2. Write code that prompts the user for their name then greets them.  Here is an example run of this program:
    What is your name? Bob
    Hello, Bob.
  3. Write code that generates three random numbers between 1 and 5, adds them up and prints ‘you win’ if their sum is above 10.
  4. Write code that prompts the user for a number and then prints whether that number is within 10 of 100.  Here is an example run of this program:
    Enter a number: 6
    No, 6 is not within 10 of 100.

Proficient

  1. Write a program which prompts a user for a line of text.  Your program should split that text into a list and then tell the user whether the first and last items were the same.  Here is an example run of this program:
    Please enter a list of items: bananas planes violins bananas
    Yes, the first and last are the same.
  2. Write code which prompts a user to enter a temperature as an integer. Your program will print “it is hot” is the temperature is over 100, “it is cold” if the temperature is under 60, and “it is just right” if the temperature is between 61 and 99 inclusive. The program continues to ask for termperatures, and evaluates them as above, until the user enters a temperature of 0.  Here is an example run of this program:
    Please enter a temperature: 95
    It is just right.
    Please enter a temperature: 110
    It is hot.
    Please enter a temperature: 32
    It is cold.
    Please enter a temperature: 0
    Good bye!
  3. Translate the following for loop into a while loop that does the same thing
    for i in range(10):
        print "i = " + str(i)
  4. Write code that prompts the user for a total bill amount at a restaurant then displays the total with a 15% tip and a 20% tip.  Here is an example run of this program:
    How much was your meal? 10
    Total with 15% tip:  $11.5
    Total with 20% tip:  $12

Ninja

  1. Write code that plays a guessing game with the user.  This time, your program should try to guess what the user is thinking.  A sample run of the program:
    Please think of a number between 1-100 and I will try to guess it.
    Are you thinking of a number between 1-100? yes
    Is it 50? no
    Is it higher than 50? yes
    Is it 75? no
    Is it higher than 75? no
    Is it 62? yes
    I got it in 3 tries!
    Are you thinking of a number between 1-100? no
  2. Write code that checks whether the content of a list is a palindrome.  For example ['p', 'e', 'e', 'p'] is a palindrome because it is the same forwards and backwards. (Hint: you may want to first write a function that reverses a list so that you can then use that to check whether the list is the same forwards and backwards)
  3. Continue working on the star chart program
  4. Look at the zip codes data file and implement some of the features described in this assignment, or come up with your own.
  5. If you have a good idea you want to pursue, you may… but make sure you’re demonstrating proficiency and not just getting bogged down in design!
Leave a response »

Assignment: Flickr wallpaper

Ms. Martin : June 7, 2010 8:51 pm : 2010 Spring Creative Computing 1

This assignment is designed to give you experience with reading and interpreting existing code while learning about the types of applications made possible by access to online information.

You will need to download flickr.py and wallpaper.py.  Make sure to save them in the same folder.  flickr.py is a library that contains functions to make calls to Flickr.  wallpaper.py is an example of a program using that library.

Run wallpaper.py a couple of times and make sure you understand what it’s doing.  READ THROUGH THE CODE ONCE BEFORE STARTING THE QUESTIONS!

Answer the following questions on a piece of paper to turn in:

  1. What is an API? (look it up and make sure you write a definition you understand, not just one you copy!)
  2. Give three examples of web-based APIs (other than Flickr).
  3. Look on the right side of this page to see the different kinds of information that can be requested from Flickr.  Come up with 2 ideas of little programs you could build (like this wallpaper one) using some of those methods.  Take a look at the app garden for ideas.
  4. Notice that both files start with a comment style we haven’t talked about which uses triple quotes (“”").  Why do you think the original authors used this comment style over the one we know? (#)
  5. Notice that in wallpaper.py, imports are done differently than the ‘from X import *’ style we know.  Take a minute to look through the file and see if you can figure out what the difference is (look at random since you’re familiar with it).  If you can’t figure it out, read the note found here.  What is an advantage of importing modules the way this program does it as opposed to how we did it?  Why do you think I showed ‘from X import *’ to you first?
  6. What does return do? Use context clues if you can’t remember or read a book chapter here.
  7. What changes would you make to wallpaper.py to have the resulting image saved as a different file name?
  8. What are two ways to make a 3×3 grid of pictures rather than the current 4×4?  Describe the changes necessary.
  9. How and why is the split() method used?
  10. On line 31 of the wallpaper.py file, a call on the photos_search function of the flickr module is made.  Notice that parameters are passed in differently from what we have learned.  Look in flickr.py to explain why the parameters are passed as tags=tags, per_page=number instead of tags, number
  11. The wallpaper.py file defines 4 functions.  Describe what input each takes and what steps it completes in detail (essentially, you should be writing pseudocode for the existing program).
  12. How many calls to the Flickr servers does the wallpaper program need to make every time it’s called?  Explain.
  13. Describe how comments are used in the flickr.py file.  Are they helpful in understanding the program?
Leave a response »

Extras: Dictionaries and Tuples

Ms. Martin : June 1, 2010 8:53 pm : 2010 Spring Creative Computing 1

I hope several of you will attempt the Star Map program.  It’s challenging, interesting and hopefully really rewarding so I strongly encourage you to attempt it!

Dictionaries

Dictionaries are used to map values called keys to data or values.   In a “real world” dictionary,  the words are keys and the values are the definitions.  Dictionaries are a lot like lists but can use arbitrary values as indexes rather than being limited to integers.  Here’s how you could visualize a dictionary that maps people’s names to their favorite foods:

----------------------------------------
|"Anna"    |  "Joe"  | "Lisa" | "Bart" |
----------------------------------------
|"Pasta"   | "Candy" | "Nuts" | "Pears"|
----------------------------------------

This is very similar to how we would visualize a list, but the indexes are “Anna”, “Joe”, “Lisa” and “Bart” instead of being 0, 1, 2, 3.

Here’s a shorthand way of building this dictionary:

>>> foods = {"Anna":"Pasta", "Joe":"Candy", "Lisa":"Nuts", "Bart":"Pears"}
>>> type(foods)
>>> <type 'dict'>

Try it at the console.  You need a series of key-value pairs separated by commas.  You can use any type for key and value.  For example, you could map a name to a list of foods they like or names to phone numbers.

In order to find out what Anna likes, you can use the following command:

>>> foods["Anna"]

See how that’s just like indexing into a list, but using a str index instead of an int?

What if you want to print what each person likes without the name?  You can loop over all the keys and use them to index into the dictionary as follows:

>>> for name in foods: # for each person in the dictionary
>>>     print foods[name] # prints a favorite food without the name

You can check to see if some value is a key in a given dictionary using the in keyword:

>>> if "Helene" in foods:
>>>     print "The teacher's favorite food is: ", foods["Helene"]
>>> else:
>>>     print "No clue what the teacher likes"
No clue what the teacher likes

Exercises

1. Write a function that reads the words in a file and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.

2. Write a function named get_letter_inventory which, given a string, returns a dictionary of letter frequencies.

Here’s how it works:

>>> h = get_letter_inventory('brontosaurus')
>>> print h
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}

Tuples

Tuples are also related to lists but like strings, they are immutable (cannot be changed).  Tuples are commonly surrounded in parentheses when created (this isn’t strictly necessary, but it makes things clearer).

>>> coords = (500, 200)
>>> type(coords)
<type 'tuple'>

Elements of tuples are accessed just like list elements using their 0-based index values:

>>> coords[0]
500
>>> coords[1]
200
Leave a response »

Project: Baby Names

Ms. Martin : May 25, 2010 7:44 pm : 2010 Spring Creative Computing 1, Courses
Thanks to Nick Parlante and Stuart Reges for the original project idea!

You will write a program that graphs name popularity for each decade since 1900 based on data given by the Social Security Administration (See their website for the latest data).

Details

  • You will read from two files: names.txt and meanings.txt. You must download them and save them in the same directory as your program.
    • names.txt: each line includes a name followed by 11 decades’ worth of popularity ranking. Notice that a ranking of 1 means the name is the MOST popular. A ranking of 0 means the name was not in the top 1000.
    • meaning.txt: each line starts with a name and continues with the name meaning. You can either present this information visually with the data graph or at the command prompt.
  • A user’s search should be case insensitive. In other words, a search for ‘MeGaN’ should find and graph the record for ‘Megan.’ You could use, for example, the .title() string method.
  • If the user searches for a name not in the files, he or she should get some kind of feedback. This can be ‘sorry, name not found’ at the command prompt or maybe a fail image displayed visually.
  • When graphing the data, notice that a ranking of 1 should be at the top of your graph, a ranking of 500 should be in the middle and a ranking of 0 should be at the very bottom. This is a tricky part to deal with. You will want to use a conditional to deal with the 0 special case.
  • You can choose what your graph looks like. It must include labels and lines for each decade spaced out at least 50 pixels. You can make a line graph or a bar graph. Below are two acceptable examples (you don’t need to graph more than one name or label each point with the name, but those are possible extensions if you finish early).

Getting started

This may seem like a really daunting program but in fact it combines many pieces we have already worked with! You should break down the program into sub-problems that you will solve one at a time.  Make sure you work with the pseudocode you will have written in class.
Here are some isolated tasks you could consider starting with:
Write code to read the data file and get a list of popularity values for a specific name entered by the user.
Write code to read the meanings file and display the meaning for a specific name entered by the user.
Write a function draw_axes that takes a graph size and position and draws the 11 evenly- spaced grid lines you will need for the 11 decades.
Write a function graph_list that takes a list as a parameter and uses Turtle Graphics to draw a graph of the list items. You should use a loop based on the list length to do this. Ideally, you would also have parameters for the size of the graph and its position.

Things you will need to know

Write with the turtle: write("<text>")

Make a string called search into all uppercase: search = search.upper()

Graphing

You have quite a bit of freedom in how you display results — pick interesting colors, a size you like, etc.  Here is one possibility:

For a challenge, try creating a line graph instead:

Grading

I understand that not everyone will finish this project in its entirety.  I will provide some of the graphing code once you have tried getting it to work on your own and it will be your task to make it work with the code you will have written.

I expect everyone to get to the point where a user can search for a name and get back popularities and meanings printed at the console.

Leave a response »

IMDB file reading

Ms. Martin : May 24, 2010 8:58 pm : 2010 Spring Creative Computing 1

Write a program that reads from the file imdb.txt and searches it for a keyword. The file is organized in the following way:

rank rating votes title (year)

You should ask the user what to search for then display ALL titles that contain that text. Here is a sample run (user input is underlined):

Search word? american
American Beauty (1999) is ranked 35 with a rating of 8.5
American History X (1998) is ranked 41 with a rating of 8.5
American Gangster (2007) is ranked 94 with a rating of 8.2

You should exactly reproduce the format shown above.  In other words, your output should be as follows:
title (year) is ranked ranking with a rating of rating

Notice that the search is case insensitive. The trickiest part will be displaying the entire title. Here is one way to do it:
1. Split each line of input
2. You know that the title always starts at index 3 of the split line
3. Use the string join method. This joins the parts of a list together into a string separated by the string it’s called on.

Here is the code you need:
title = " ".join(tokens[3:])
What this does is squish together all parts of the title into one string separated by spaces.

Leave a response »

Robots and lists

Ms. Martin : May 23, 2010 3:42 pm : 2010 Spring Creative Computing 1

In the coming days, we will be coming back to lists to perform interesting data manipulation. To ease our way back, let’s do a few list exercises involving robots.

Activity 1: Home movie

Get your robot to film and display a “movie” by storing then showing a list of pictures.  I’ll have shown you the basic idea in lecture but it will be up to you to figure out appropriate timing to get about 10 seconds of video without blurring while your robot is moving.

Activity 2: Note list

You all wrote songs using a series of beeps.  Didn’t that look repetitive?  Create a list of beep frequencies then loop through that list to write a song more efficiently.

Notice that if you only have a list of frequencies, you’re somewhat limited because the length of each beep stays the same.  Write code to use two lists to define a song: one of frequencies and one of beep lengths.

Activity 3: Images as lists of pixels

It can be very useful to think of images as lists of pixels or picture elements, the tiny dots pictures are made of.  Given this view, we can loop over the pixels in an image and manipulate then in certain ways.

We can use two functions, getWidth(<picture>) and getHeight(<picture>) to know what loop bounds to use.  For example, the following code will loop through a picture the robot just took and make a horizontal line 20 pixels from the top of the image green-tinted:

for i in range(getWidth(pic)):
    pixel = getPixel(pic, i, 20)
    setGreen(pixel, 255)
    repaint()

Try it! Notice that the i variable gets values from 0 to the width of the whole picture. We fetch a particular pixel and tint it. In this case, we repaint the image as the line is being drawn. Modify the code to repaint the picture only after the line is drawn.

What if we wanted to tint the whole image?  We need to vary both the x and the y coordinates of the pixel we are fetching.  To do this, we’ll need to nest two for loops, one changing the x coordinate and another modifying the y:

for i in range(getWidth(pic)):
	for j in range(getHeight(pic)):
		pixel = getPixel(pic, i, j)
		setGreen(pixel, 255)
repaint()

In the example above, I repaint only after the whole image is tinted. Change the position of repaint() to change when the image is updated.

What is the 255 business?  Colors of pixels are represented as a combination of red, green and blue.  Each color can have a value between 0-255.  In this case, we are asking the computer to make each pixel in the image have as much green as possible.  Experiment with different values of green.

Can you tint the video you made in the first exercise?

Leave a response »

Robot activities

Ms. Martin : May 11, 2010 9:02 pm : 2010 Spring Creative Computing 1

Work on these activities in your group.  If you are getting done early, GREAT!  I want to see you continuing to work with the robots in cool ways.  Feel free to skip around and to simply experiment.

Activity 0: song

Write a song function as outlined in the tutorial.

Activity 1: go function

Write a function named go that takes distance as a parameter and makes the robot go that many inches.  To do this, you will need to experiment with how much distance a robot covers over different amounts of time and write an equation to relate distance to time.  To do this, you may want to get a marker and have your robot draw lines that you can then measure with a ruler.

The call go(6) should make your robot go 6 inches, the call go(0) shouldn’t do anything and a call on go(1.5) should make your robot go 1.5 inches.  Try to be as precise as you can, but don’t worry too much about it.  It’s going to be impossible to get it exactly right!

Activity 2: random movement

Write a function that makes your robot go forward a random number of inches between 1 and 6, then turns a random amount (range of your choice) and repeats.  Your function should take one parameter: how long the robot should repeat this for.  For example, the call rand_moves(10) should make your robot make random moves for 10 seconds.  Similarly, a call on rand_moves(15) should make your robot move randomly for 15 seconds.

Activity 3: pictures

Write a function that will take a picture, show it, wait 3 seconds, go forward 1 second.  Your function should take one parameter: the number of times to repeat this.  For example, a call on pictures(10) should make your robot take a picture, display it, wait 3 seconds, go forward 1 second and repeat the whole thing 10 times.

Activity 4: random pictures

Write a function that will make your robot go forward and turn randomly and then take a picture.  Once the picture is shown on the screen, the user should be asked whether the picture shows what they’re looking for.  Your robot should repeat this behavior until the user says that yes, they saw what they were looking for.  For example, if your robot is meant to be looking for a whiteboard eraser that’s a couple of feet away, you might have to say no to three or four pictures before the robot orients itself such that your camera takes a picture of the eraser.

Activity 5: creep bot!

Combine your knowledge of the joyStick() command with taking pictures to have your robot repeatedly take pictures as you drive it around.  How well can you navigate without seeing your robot?

Activity 6: “Theremin”

You will write a program that beeps at different pitches based on the light sensor values.  For example, I wrote one that just adds up the three sensor values and uses that as the beep frequency.  I had mine loop for 20 seconds so that as I approach my hand to the robot, the pitch gets higher and higher.  This behavior is roughly based off of an interesting instrument called the Theremin.  Look it up!

Activity 7: Cockroach function

Your cockroach function will take one value as a parameter: the length of time the robot should move for.  Your cockroach should flee light and go towards darker places.  So, for example, if you start it near the edge of the shadow of a table, it should go under the table.  There are a few ways to implement this, but here is a simple one:

  1. read all three light sensor values
  2. if the left light sensor gives a value less than both the middle and the right light sensor, move right (remember, a low value means a bright light)
  3. if the right light sensor gives a value less than both the middle and the left light sensor, move left
  4. otherwise, go forward

Activity 8: Obstacle avoidance

The following code is the start to an obstacle avoidance program.  See if you can figure out what it does from reading it, then save it and run it.

while timeRemaining(30):
    if getObstacle("right"):
        backward(1, .1)
        turnLeft(0.7, .1)
    elif getObstacle("left"):
        backward(1, .1)
        turnRight(0.7, .1)
    else:
        forward(.5)
        wait(.1)
stop()

Right now, it’s not so hot.  What happens if you make your robot run this program while it’s directly facing a wall?  It just crashes, right?  That’s because we’re totally ignoring obstacles right in front of us!  Add a case for when there’s something right in front.  Your robot should go backwards then pick randomly with equal probability to either turn right or left.

Next, make your robot beep when it sees an obstacle.  You should use three different pitches and tone lengths for the three different obstacle positions so you can hear what your robot is doing.

Finally, make your robot stop and take a picture whenever it runs into an obstacle.

1 Comment »

Introduction to Scribbler Robots

Ms. Martin : May 11, 2010 8:50 pm : 2010 Spring Creative Computing 1

Robots are one of those things we all think we know something about but that are surprisingly difficult to define.  Broadly, a robot is a program that runs automatically without a human needing to interfere.  Robots have logic of varying complexity that allow it to react to different situations on its own.  Given this definition, a robot doesn’t technically need to be a physical machine like the Wall-Es and Transformers found in movies.  One type of robot all of us depend on without necessarily realizing it is a webcrawler which indexes web content automatically to make search engines like Google possible.

For the next few days, we’ll be learning to program the Scribbler robots.  These are simple little “tank” robots that have a number of sensors including a color camera, infrared sensors and light sensors.  Our computers will connect to them using bluetooth which is short-range and reasonably fast.

I HIGHLY ENCOURAGE YOU TO CHECK OUT SAMPLE PROGRAMS!

scribbler

In order to start using your robot, you have to make sure that your bluetooth dongle is connected to the computer.

python for robots

You will need to click on the desktop icon that says ‘Python for ROBOTS.’

Once IDLE loads up, type in these commands:

from myro import *
init("com3") # or whatever com port your bot has

Unfortunately, the com port seems to change all the darn time.  In order to find it for your particular connection, you will need to right-click on the bluetooth icon in the system tray then select ‘Add bluetooth device.’  Find the serial number of your robot, click next, then you should use whatever outgoing com port is displayed in your call on the init function.

Your screen should look like the following:

commands

You should get a popup asking you to accept the bluetooth communication.  Click on it:

bluetooth

You should then be asked for a bluetooth passkey.  Type in 1234 as follows:

passkey

To personalize your robot, you can give it a name.  For example, to name a robot “Terminator”

>>> setName(”Terminator”)

You are now ready to send commands to your robot!  For today, I want us to make sure there are no technical hurdles and then experiment with some of the basic commands.  To start, try typing in joyStick() and use the mouse to direct your robot around the room.  How far can it get before it is out of range?  Make sure you’re doing this on the floor so your bot doesn’t fall off the table!!

Your robot can produce songs!  This is going to get pretty annoying, but it’s in the name of learning, right?  Each group is going to write a robot song.  The basic idea is that you will be using a beep command.  Try this:

>>> beep(1, 440)

You should have heard a tone play for 1 second at 440Hz.  Hz?  Hertz is a mesure of frequency.  beep is a function that creates waves at specified frequencies.  It turns out that 440 is the frequency of an A.  Try creating a beep at a higher frequency:

>>> beep(1, 800)

It sounds higher-pitched, right?  The human ear can hear roughly between 20 Hz – 20 kHz.  Can you hear a beep(1, 20000)?  What about beep(1, 20)?

In order to create your song, you will create a function.  For example, I will call mine mySong.  Here is what my code looks like:

song

I encourage you to download robotsong.py (just click on the link at left or on the calendar) and play it yourself.  To play the song, go to ‘Run Module’ as follows:

run

When you are ready to write your own robot song, go to ‘File > New Window’ and get a new program file.  Save it using a descriptive name of your choice and make sure it has .py at the end!

Once you’ve written your song, explore the following functions and complete the questions at the end.  Keep in mind that all the Python you already know still applies!

Movement

joyStick()
Pops up a window that allows you to move the robot using a mouse-driven joystick.

backward(SPEED, SECONDS)
Move backwards at SPEED (value in the range -1.0…1.0) for a time given in SECONDS, then stop.

forward(SPEED, TIME)
Move forward at SPEED (value in the range -1.0…1.0) for a time given in seconds, then stop.

stop()
Stops the robot.

turnLeft(SPEED, SECONDS)
Turn left at SPEED (value in the range -1.0..1.0) for a time given in seconds, then stops.

turnRight(SPEED, SECONDS)
Turn right at SPEED (value in the range -1.0..1.0) for a time given in seconds, then stops.

wait(TIME)
Pause for the given amount of TIME seconds. TIME can be a decimal number.

Pictures

pic = takePicture()
show(pic)

The first line commands the robot to take a picture and save it in a variable called pic. The second line displays this picture on the screen.

grayPic = takePicture("gray")
show(grayPic)

This example is very similar to the previous but the picture is black and white.  Taking a black and white picture is less time-demanding.

Sensors

Your robot has sensors that senses different aspects of its environment. The image below shows two types of sensors that your robot has – proximity and light sensors.  Notice that they’re on the opposite side of the robot as the camera so you will have to drive backward to use them!

ScribblerSensorDiag

The following is a list of external stimuli that the robot can sense and a description of how the robot senses them.

  • Light: There are three light sensors on your robot. These are located in the three holes on the front of your robot. These sensors can detect the levels of brightness (or darkness). Your robot can use these sensors to detect variations in ambient light in a room.
  • Proximity: At the front of the robot you will see two tiny lamps on each side of the robot. These are IR emitters. If the light that is emitted by these sensors get reflected by the presence of an obstacle, then the light will bounce back towards the robot and is captured by the IR sensor that is present in the tiny notch in the middle of the two IR emmiters (see figure above).
  • Line: If you look at the front portion of the Scribbler’s chassis (away from the third wheel), you will notice two pairs of tiny holes. These are also IR emitters and receivers and can be used to detect lines on the floor.  THIS SENSOR IS REALLY FLAKY!  USE AT YOUR OWN RISK.

Once you are familiar with your robot’s sensors, you can use them to create interesting creature-like behaviors for your Scribbler.

Enter the following command in the Python Shell:

>>> senses()

Scribbler Sensor Values:

  • Light: The values being reported by the three light sensors are: 135 (left), 3716 (center), and 75 (right). In general, the lower the values, the brighter the light being sensed. This snapshot was taken when the center light sensor was covered by a finger.
  • Line: In the presence of a line under the Scribbler (the line has to be aligned with the length of the robot) the Scribbler can detect a bright edge against a dark edge (that forms a line). The display shows the values of left and right sensors (both are 1). If the right sensor is on a dark area of an edge or a line and the left sensor is on a lighter area or edge, the sensor values would be (left=0, right=1). If the edge is reversed, the values would be (left=1, right=0).
  • IR: The IR values displayed are also left and right (in the same orientation as the light). Their values will be either 1 or 0. If there is an obstacle detected, the value will be 0. It is 1 otherwise.

Unfortunately, some of the sensors are pretty flaky.  Try to get the line sensor to get different values for left and right, for example.  It doesn’t really happen, so it’s not very useful!

Obtaining Sensory Information

In addition to using the senses operation, you can use various functions in the Myro library to obtain these sensor values.  You can use these functions as tests for loops or conditionals to make your robot react to its environment.

Light Sensors

  • getLight(<POSITION>): This returns the current value in the <POSITION> light sensor. Your Scribbler has three light sensors (see picture above). <POSITION> can either be ‘left’, ‘center’, ‘right’ or one of the numbers 0, 1, 2. The positions 0, 1, and 2 correspond to the left, center, and right sensors. For example, keep your robot in the same position and try the following:
>>> getLight('left')
>>> getLight(0)
>>> getLight('center')
>>> getLight(1)
>>> getLight('right')
>>> getLight(2)

Proximity Sensors

  • getIR(<POSITION>): This returns the values of the IR sensors. <POSITION> can be 0 or ‘left’ and 1 or ‘right’. Try the following:
>>> getIR('left')
>>> getIR('right')
>>> getIR(0)
>>> getIR(1)

Obstacle Sensor

obstacleSensor

The Fluke dongle has an additional set of obstacle sensors on it. These are also IR sensors but behave very differently in terms of the kinds of values they report. The following functions are available to obtain values of the obstacle IR sensors:

  • getObstacle() Returns a list containing the two values of all IR sensors
  • getObstacle(<POSITION>) Returns the current value in the <POSITION> IR sensor. <POSITION> can either be one of ‘left’, ‘center’, or ‘right’ or one of the
    numbers 0, 1, or 2. The positions 0, 1, and 2 correspond to the left, center, and
    right sensors.  Try the following:

    >>> getObstacle()
    >>> getObstacle('center')
    >>> getObstacle(1)
    >>> getObstacle('right')
    >>> getObstacle(2)
    >>> getObstacle('left')
    >>> getObstacle(0)

Repetition

You can use any of the loop techniques we’ve discussed so far.  Using them with sensor values is particularly powerful.  For example, you may want your robot to keep going forward while the light sensor gives values below a particular threshhold.

One very useful Scribbler-specific way of looping allows your robot to do things for a certain amount of time.  To do so, you’ll want to use the Scribbler timeRemaining(SECONDS) function.  For example:

# make the 'bot print a message and go forward for 10 seconds.
while(timeRemaining(10)):
    print "Gogogo!"
    forward(1) # this makes your 'bot go forward at full speed forever!  Until the stop() command is called.
stop()

On to ACTIVITIES!

Leave a response »

Lists exercises 2

Ms. Martin : May 4, 2010 8:35 pm : 2010 Spring Creative Computing 1

Please take your time going over the list tutorial and the first set of exercises.  Once you are comfortable with those, take a look at the advanced list examples and move on to these.

As usual, please jump around as you wish.

Activity 1: Magic Eight Ball (Jason’s idea!!)

Create a program that prompts the user for a question then gives a magic eight ball answer.  Your program should randomly pick an answer from a list of choices.  Feel free to use the standard answers listed on the Wikipedia article or to make up your own creative ones.  Your program should keep asking the user for questions until he or she types “exit.”

This is one that can easily be expanded.  You could use Turtle Graphics to show a visual representation of the Eight Ball.  You could  report how many positive and negative answers were given.

Activity 2: Temperature Conversion

Remember writing a temperature conversion function?  Either dig it out or write it again.  Your program should start with a list of temperatures in Celsius, should convert them to Fahrenheit and store the results in a second list then print out both lists.

Activity 3: Multiplication table

Prompt the user for a number.  Use the range function to print out a multiplication table for numbers between 0 and the desired bound.

Activity 4: Dice statistics

Write a program to roll a die 200 times then report how many 1s, 2s, 3s, etc were rolled.  Draw a histogram of the data using Turtle Graphics.

Activity 5: Cards

Write as short of a program as possible to generate a list of all 52 cards in a standard card deck.  You can choose how to represent cards.  I recommend doing something like building strings that first have the rank then the suit.  For example, the list might start with ["1club", "2club", "3club", ... "kingclub"...]  Then, shuffle the resulting deck and print it out.

Leave a response »
« Page 1, 2, 3 »