Button Fun

November 3rd, 2009 by Lizabeth Arum No comments »

This was my example. When you clicked the button, the face appeared and a sound file of a scream played.
I also suggested, to help students understand the interaction, that they could start with a picture of an animal, like a pig. If you clicked the tail, the image should change and a squeal should play.
surprise

iPhone Project with buttons and sound

  1. Create a background image

  2. Create a foreground image

  3. Create an icon image 57 x 57px

  4. Find a sound. Open the sound in Audacity and save as 32-bit sound.

  5. Open XCode

  6. Create a ViewBased Project

  7. Add the images and the sound

  8. Update the plist file

  9. Add a framework by CTRL+clicking on Frameworks. Select Existing Frameworks and add AudioToolbox.framework
    add_framework

  10. Open the header file

  11. Create a statement that imports the AudioToolbox/AudioToolbox.h

  12. Add 3 IBOutlets. One to hold a UILabel and the other two to hold pointers of type UIImageView

  13. Create a pointer of type NSTimer and name it resetTimer

  14. Create a a variable named sound of type SystemSoundID

  15. Create 3 @property declarations for the label and the UIImageViews

  16. Create a buttonPressed IBAction that takes sender of type id as its parameter.

  17. Open the implementation file

  18. @synthesize the properties

  19. Define the buttonPressed method:
    1. Set the text of your label to your message

    2. Create a pointer named foregroundImg of type UIImage and set it to the UIImage method imageNamed with the name of your foreground image as your parameter

    3. Set the image of the UIImageView that will pop up, to be the variable you just created (foregroundImg)

    4. Set the hidden property of that UIImageView to NO

    5. Test if sound and

      if the condition is met, then call:
      AudioServicesPlaySystemSound(sound);

    6. Test if resetTimer does NOT equal nil

      If the condition is met, then call:
      [resetTimer invalidate];

    7. Now set resetTimer to
      resetTimer = [NSTimer scheduledTimerWithTimeInterval:1.1 target:self selector:@selector(resetImages:) userInfo:nil repeats:NO];

  20. Now you have to define the method you just called (resetImages)


    - (void)resetImages:(NSTimer *)sender{

    }

  21. Inside the method:
    1. Set the hidden property of the UIImageView that pops up to YES

    2. Empty the label.

    3. Set resetTimer to nil

  22. Navigate to and uncomment viewDidLoad

  23. After the call to super, include these lines (remember to update the name of your audio file):

    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundUrlRef = CFBundleCopyResourceURL(mainBundle, CFSTR ("aaaah2"), CFSTR ("wav"), NULL);

    // Create a system sound object representing the sound file
    AudioServicesCreateSystemSoundID (soundUrlRef, &sound);

  24. Open the nib file and add a UIImageView

  25. Using the inspector set it to hold your background image
  26. Add a label

  27. Add a button
    bgImage

  28. Add another UIImageView and align it with the bottom
    bottom

  29. Connect The File Owner to label and select label
    to_label

  30. Connect the button to the File Owner and select buttonPressed
    btn

  31. Connect the File Owner to the UIImageView aligned to the bottom and select the name holding the UIImageView that pops up
    imageView

This project was inspired by Rory Lewis’s tutorials

Some early projects

November 2nd, 2009 by Lizabeth Arum No comments »

Physical Computing

Here are a few of the recently completed projects:P1120064
FSR and LEDs

MovieA soft circuit button and LEDs

light4
Potentiometer controlled LEDs with 2 modes controlled by a button

img3
FSR controlled spooky eyes

A few other interesting projects are in the works. Two involve the capacitive sensor. The first uses a hacked disposable digital camera that flashes when the sensor is triggered. The second project was created as a Halloween installation. I hope there were pictures!

A Short Week

October 16th, 2009 by Lizabeth Arum No comments »

I finished my soft circuit. Now when you pet it it purrs and flashes its eyes. I added a homemade capacitance sensor and a vibrating motor. I started with this information, but ended up using Paul Badger’s CapacitiveSense003 library which worked great. My circuit uses a 2.2MΩ resistor to connect pins 2 and 5 and the sensor itself is made of conductive frabric from LessEMF. The piece came from the Fabric Sample Set (Cat. #SAMPLER) and I cut in in half and connected it to pin 2 through conductive thread and a 22 AWG hookup wire.

Here’s the code:

#include
const int purr = 9; // pin that the LED is attached to
const int led = 3; // pin that the LED is attached to
const int eye1=10;
const int eye2=11;
const int mouth=4;
boolean purring=false;
boolean openEyes=false;
CapSense cs_1_2 = CapSense(1,2);

void setup(){
pinMode(purr, OUTPUT);
pinMode(led, OUTPUT);
pinMode(eye1, OUTPUT);
pinMode(eye2, OUTPUT);
pinMode(mouth, INPUT);
pinMode(led,OUTPUT);

pinMode(purr,OUTPUT);
digitalWrite(purr, LOW);
Serial.begin(9600);
}

int touch_sensor(){
long start = millis();
long total1 = cs_1_2.capSense(30);
if (total1<02){
return 1;
}else{
return 0;
}

/*Serial.print(millis() - start); // check on performance in milliseconds
Serial.print("\t"); // tab character for debug windown spacing

Serial.print(total1); // print sensor output 1
// print sensor output 3

delay(10); */
}

void loop(){
int touch=touch_sensor();
if (digitalRead(mouth)){
openEyes=true;
}
else{
openEyes=false;
}

if(!touch){
if(purring){
for(int i=255;i> 0;i-=10){
analogWrite(purr,i);
delay(20);
}

purring=false;
}
else{
analogWrite(purr,0);
openEyes=false;
}
digitalWrite(led,LOW);

}
else{
purring=true;
digitalWrite(led,HIGH);

analogWrite(purr,200);
openEyes=true;

}
if (openEyes){
for(int i=65;i<255;i+=10){
analogWrite(eye1,i);
analogWrite(eye2,i);
delay(10);
}
for(int i=255;i>65;i-=10){
analogWrite(eye1,i);
analogWrite(eye2,i);
delay(10);
}}else{
analogWrite(eye1,0);
analogWrite(eye2,0);
}
}


Students worked on their own soft circuits this week with different enthusiasm levels. Students used to working through labs, but not producing pieces, enjoyed this assignment far less than those who like to make crafts. Still, I believe introducing students to conductive thread and conductive fabrics will help them construct later projects.

We did run into a few glitches this week as well. One student plugged 12V into the freeduino. The 12V plug was used in our first experiments, and I had mentioned that the freeduino could be powered by the USB or a battery. I had extra Atmega chips and, apart from the chip, the board seemed fine.

Another student had trouble finding the usbserial port. At first I thought that the FTDI Drivers for Intel Macs was not installed, but then he moved to another computer with the same problem. His circuit seemed fine. In the end, it turned out that the USB cable was to blame. As soon as we switched cables, everything worked. It was a brand new cable and it surprised both of us that this was the source of the problems.

IPhone programming is going a bit slower than I anticipated. The class was still working on the second version of the Browser assignment this week. In the meantime, I came up with a way for students to create web pages to document their work:


Background-color:

Application name:


Notes:


File Name:


Code:

 

The Blender class is going well. Students have started working with armatures and materials. They have made short quicktime movies of the experiments and everyone is still engaged in the process.

A cute soft circuit project

October 6th, 2009 by Lizabeth Arum No comments »

Here’s a soft circuit with 2 LEDs and a button. It is basically an electronic sock puppet.

I used a sock covered in a knitted bag. The button is a sewing snap. When the mouth closes, the button returns a 1 and the LEDs flicker.

height="850" codebase='http://www.apple.com/qtactivex/qtplugin.cab'> controller="true" loop="false" pluginspage='http://www.apple.com/quicktime/download/'>

Here’s the code

#define btn 4
#define led1 3
#define led2 9
int btnState;

void setup(){
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(btn,INPUT);

}

void loop(){
btnState=digitalRead(btn);
if(btnState){
for(int i=50;i<255;i+=5){
analogWrite(led1,i);
analogWrite(led2,i);
delay(10);
}
for(int i=255;i>100;i-=5){
analogWrite(led1,i);
analogWrite(led2,i);
delay(10);
}
}else{
digitalWrite(led1,LOW);
digitalWrite(led2,LOW);
}
Serial.println(digitalRead(btn));
}

iPhone Browser

October 6th, 2009 by Lizabeth Arum No comments »

Perhaps the most typical network task performed by many network
applications is to load a web page.

The functionality of
Safari’s WebKit engine is available to you in the form of the UIWebView.

What we did

Created an application that loaded web pages.

  1. Open Xcode:

  2. Create a new Project (⌘+⇧+N). Make it a View-based
    Application

    view_based

  3. Name it Browser

  4. Open BrowserViewController.h and add pointers for IBOutlets
    for urlField (a UITextField) and webView (a UIWebView).

  5. This application brings up the keyboard. You will
    be managing a text field and you will want to dismiss the keyboard when the user either clicks a done button or presses return.

    To dismiss the keyboard, you need to tell the text field to give up its role
    as the first responder, meaning the component that initially receives
    the user input.
    [nameField resignFirstResponder];

    If you look up the documentation for UITextField, you’ll see that it has a delegate property
    that is defined by the UITextFieldDelegate protocol, a defined group of
    related methods.
    UItextFieldDelegate_doc

    Look up this protocol and you’ll see it has numerous
    methods that alert the delegate of events relating to the text field. One
    of them is textFieldShouldReturn, which looks like what you need in order
    to know when the user has tapped return.

    Add
    the UITextFieldDelegate protocol declaration too.


    @interface BrowserViewController : UIViewController <UITextFieldDelegate>{

  6. Add an instance
    method to handle the clicking of the go button. It will be of type IBAction Name it handleGoTapped.Pass it (id)sender

    Instance methods follow the closed curly brace and precede the @end

  7. Open the BrowserViewController nib in IB and create the User Interface.
    • A textField
    • A webView
    • A GO button

    Add a Placeholder in the textField so that the user knows to type http:// and set the keyboard to URL (⌘+1)

  8. Make the connections.
    (control-click the text field to expose its outlets, and connect
    its Delegate to File’s Owner.)

  9. Open up BrowserViewController.m. You’ll need to define the method to get the URL from
    the text field and have the web view load that site; this method will be
    called when the user clicks the Go button or when they hit Return
    on the pop-up keyboard.

    When the go button is pressed:

    1. Close the keyboard by calling resignFirstResponder on
      urlField

    2. Call loadURL on self

  10. To create the loadURL method
    1. Create a pointer named url of type NSURL and set it to:

      [[NSURL alloc] initWithString: urlField.text]

    2. Create a pointer named request
      of type NSURLRequest and set it to
      [[NSURLRequest alloc] initWithURL: url]

    3. Call loadRequest on webView and pass it request
    4. Release request
    5. Release url

  11. Add the following method:
    -(BOOL)textFieldShouldReturn:(UITextField *)textField {

    }

  12. Inside the method:
    1. Test if the textField equals the urlField

    2. Close the keyboard with resignFirstResponder
    3. Call loadURL on self
    4. Outside of the conditional, return YES

  13. Implement autoroatation
    -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return ((interfaceOrientation == UIInterfaceOrientationPortrait) ||
    (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
    (interfaceOrientation == UIInterfaceOrientationLandscapeRight) ||
    (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown));
    }

  14. Save, Build and Run

  15. Enter a url to test

  16. The most obvious thing lacking from
    the example is the usual forward and back buttons. You can
    implement them with the UIWebView’s goForward and goBack methods. Provide a delegate that implements the UIWebViewDelegate.

Part 2

All the substantial work in this application is done
by the UIWebView. Once you’ve loaded the page, this view — backed
by the WebKit engine for rendering HTML, interpreting JavaScript, and
handling the network communication — does all the work for handling your web interactions, including submitting forms, navigating to new
pages, running client-side browser apps, etc.

Even if you’re not planning on developing a browser, the UIWebView
has other compelling uses. While UIKit doesn’t provide a styled text
component for iPhone apps, you can style HTML to your heart’s content
with CSS, and put that styled HTML into a UIWebView. In fact, this is
an excellent way to provide an about screen for your application, as
you can provide links to your application’s home page, e-mails for tech
support, or even dialable phone number links, all by just authoring
HTML.
To do this, instead of loading a page from the web, you can include
your HTML, CSS, and images in the application bundle, and then find
them inside the bundle. Making a URL from a path in the bundle is just
a matter of converting the path string to an NSURL:

  1. Create a web page named mywebpage.html or use index.html

  2. In the
    <head></head> section add the following:
    <meta name="viewport" content="width=device-width; initial-scale=1.0;" />
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
    <meta name="apple-mobile-web-app-capable" content="yes" />

  3. Set css body margin to zero

  4. Add the web page to your project. CTRL+click on Resources. Copy the file to your project.

  5. Create an application like you made in part 1, Name it Browser2.

  6. This application is the same as the previous except for the loadURLmethod. Create the IBOutlets and IBAction in the header file

  7. Open Browser2ViewController.xib create a text filed, web view and button. Make connections and CTRL+click on the textField and link it to the FIle Owner’s delegate.

  8. Open the Inspector and in the Text Field set the Text to webpage:

  9. This application is the same as the previous except for the loadURLmethod. Open Browser2ViewController.m file and define the IBAction method and then create the loadURLmethod

    //fill in the blank with a keyword to show your page
    //I did webpage:
    NSRange range = [urlField.text rangeOfString: @"______:"];
    NSURL *url = NULL;
    if (range.location == 0) {
    // find the about page in bundle

    NSString *myPath =
    //fill in the blank with the name of your page
    [[NSBundle mainBundle] pathForResource:@"______"
    ofType:@"html"];
    url = [[NSURL alloc] initFileURLWithPath: myPath];
    } else {
    url = [[NSURL alloc] initWithString: urlField.text];
    }
    if (url != NULL) {
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
    [webView loadRequest: request];
    [request release];
    [url release];

    }

  10. Add the following method:
    - (BOOL)textFieldShouldReturn:(UITextField *)textField {

    }

  11. Inside the method:
    1. Test if the textField equals the urlField

    2. Close the keyboard with resignFirstResponder
    3. Call loadURL on self
    4. Outside of the conditional, return YES

  12. Implement autoroatation
    -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return ((interfaceOrientation == UIInterfaceOrientationPortrait) ||
    (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
    (interfaceOrientation == UIInterfaceOrientationLandscapeRight) ||
    (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown));
    }

  13. Save, Build and Run

  14. Modify the loadURL method so that if the urlField is empty or if the urlField contains the text webpage:, your page gets loaded.

  15. Add the ability to go forward and back

Freeduinos!

September 30th, 2009 by Lizabeth Arum No comments »

Both my middle school and high school classes worked on putting together the Freeduino kits.
yhst-82942516561161_2071_4704635
In order to avoid any soldering mistakes, I asked students to place all there resistors in the board first, and once I checked them, they could solder away. Capacitors were next, then LEDs then everything else. The middle school class had more success with putting the kits together quickly. Maybe soldering was more of a novelty for them? They completed their boards within two classes, but the high school students had the potential to drag the process into a third class. Rather than do that, I finished all but one of the boards. There was one high school student who completed his Freeduino over the weekend and worked on the Proto Shield from Adafruit in class.

My intention was to also have both groups make Proto Shields, but now I’m thinking that that project should be optional.

More Objective-C Hello World

September 28th, 2009 by Lizabeth Arum No comments »

So, the joke in class was “will there be a HelloWorld27?”

Probably not, but we are up to HelloWorld4.

So the class is small, but made up of students with very different programming backgrounds. Two of the students are very comfortable in the Revolution environment, but are having some difficulty getting used to the C syntax. The other four students have used Java and/or Arduino, and while the syntax is different, they are finding it easier to adapt what they know to what we are doing.

I find for some students pictures are essential.

HelloWorld04

  1. Create a an image of yourself with the following dimensions:
    dimension
  2. Save it as a png on the desktop

  3. Open Xcode and create a new project

  4. Create a View Based application
    view_based

  5. Save it as HelloWorld04

  6. Open up the HelloWorld04ViewController.h file

  7. Create a UILabel pointer named label of type IBOutlet

  8. Below the closed curly brace create an (IBAction) named hello and pass it (id)sender

  9. Open the Implementation file and define the hello function so that the text of label is set to a message

  10. Save the files

  11. CTRL+click on the Resources folder and add the png. Make sure to Copy items into destination group’s folder(if needed)

  12. Open up the main nib file

  13. Double click on the HelloWorld04ViewController in the MainWindow.xib
    viewController
  14. Click on the link
    link
  15. From the library add a UIImageView

  16. In the attribute window set the image to your png

  17. From the library drag a UILabel onto the view. Adjust the size

  18. Clear the Text in the Text field

  19. Choose a color for the text in the attribute window

  20. From the library drag a button on to the view and change the label on the button to Press Me

  21. In the xib window click on File’s Owner and press ⌘+2.

  22. Connect label to the label in the view.

  23. connect hello: to the button and select Touch up inside

  24. Save the xib file

  25. Build and run

  26. Modify the code so that the text keeps toggling between two expressions.
    animation
  27. Add an NSLog() statement to print out the current text to the console.

  28. Save the xib file

  29. Build and run (⌘+⇧+R)

A Tone Generator and a Cool Purchase

September 24th, 2009 by Lizabeth Arum No comments »

A few years back, I took a summer physical computing class at Parsons with Dan Mikesell. For our first circuit he gave us the following schematic and image to work with:
555circuit555pinout
I like this assignment because it introduces an IC chip, the NE555 Timer, and it makes an awful noise when it works. I also like it because initially it seems hard, but when students take a moment to think about the connections, it turns out to be quite simple. I always tell students to start with the GND and Vcc pins and go from there. It’s like solving a puzzle.

After displaying the schematic, I hand out a bag with the components. For each student, or group of students, I remove the components from the bag, name them, and describe their function. Then I leave students alone to figure out the wiring.

Today was Middle School Physical Computing and it was the last class of the day. Everyone was exhausted, but we still managed to play with the LED Resistor Calculator and two students out of eight were able to generate annoying tones.

Success!

I also purchased the Makerbot CupCake CNC for school today. Makerbot describes the “CupCake CNC as a rock solid open source 3D printer that is easy to build, easy to run, and easy to use. Its 100% open source, built to be hacked, and beginner friendly.” The plan is to have the High School students research digital fabrication and then build the printer in November. Very cool!

Piranha Leds and LED Resistance Calculators

September 22nd, 2009 by Lizabeth Arum No comments »

It was the first Middle School Physical Computing class of the week today. Class was split between two activities. The first was lighting a 5mm Flux RGB LED piranha. While not told whether they had a common cathode or common anode LED, students were given the following information:
rgb_piranha
DC forward current 20mA
Red: 2V typ, 2.4V max
Green: 3V typ, 3.6V max
Blue: 3V typ, 3.6V max

After determining their resistor values, each student wired up their circuits to discover if their led was common cathode or common anode. Only one student managed to burn out the led by wiring both sides to power.

After creating some blended colors, students put the lights aside and went on to construct Evil Mad Scientists’s LED Resistance Calculators.

Next class we’ll put the calculators to use and solve a few problems!

Our First IPhone App

September 21st, 2009 by Lizabeth Arum No comments »

I’m teaching a year long iPhone programming class to middle school students. The only prerequisite for the class is one year of programming. Some of them have worked with Actionscript, Processing and Arduino. Others only have experience with Revolution.

I’ve tried to prepare the kids for the work that is involved. I’ve told them that graduate students at ITP were told that their iPhone programming class was going to be harder than any other programming class they’ve taken. In spite of my warnings, no one was scared off.

To get the ball rolling without talking about Objective-C, students worked on 2 simple applications. The first one, which is included below, is your basic Hello World app. In addition to creating a label, students also got to create their own icons for their applications.

The second application was a View-Based Application that modified the code in the implementation file so that the content could turn when the device is turned.

Everyone in the class completed the first part. There were two students that were confused about what a .png was and renamed their photoshop images with the .png extensions. After struggling to get their icons to show up, I’m pretty sure they won’t make that mistake again!

Overall, everyone was engaged and the energy level was high. Not bad for the last class of the day.

Hello World

xib files used to be called nib files and Apple continues to refer to them as nib files regardless of their extention.

Nib files are composed of several parts

  • File’s Owner
  • First Reponder
  • View—instance of UIView class

Part 1

  1. Open Xcode and create a new project (⌘+ ⇧+N)
    open_Xcode

  2. Select application under the iPhone icon on the left

  3. In the right panel select Window-Based Application, then press Choose. Save the project
    windows
  4. Double-click on the nib file to open
    Interface Builder
    nib

  5. Open Library (⌘+⇧+L)
    open_library

  6. Scroll down until you see a label icon.

  7. Drag from library to view

  8. Open Inspector (⌘+ ⇧+I)
    open_inspector
  9. Modify label so that you pick a size, color, drop shadow and a message.
    label_inspector

  10. Save

  11. In Xcode click on Build and Run

Interface Builder creates Objective-C objects and serializes those objects in to the nib file so that they can be loaded directly into memory at runtime.

Make sure that if you have an iPhone, your actual iPhone is not plugged into the computer while developing iPhone applications.

HelloWorld

Part 2

  1. Open your last project in the Simulator

  2. Click on the Home Icon
    home_icon

  3. Look at your application icon
  4. You need to create a .png icon 57 x 57 pixels. In Photoshop create your icon. Don’t worry about applying the button effect to it, it will happen automatically. Save it as icon.png

  5. Select the Resources folder and choose Add to Project from the Project menu and navigate to the icon. Choose Copy items into destination group’s folder(if needed).
    importing_icon
  6. In Xcode expand the Resources folder. Click once on Info.plist. This property list contains general information about the application you are building, including the name of the icon file.

  7. Find the row with the label Icon file. Double click on the empty cell to the right of the label and type in the name of your png file
    plist
  8. Locate Bundle identifier. The standard naming convention is to use com or org followed by a period, then the name of the organization, another period and the name of the application.

  9. compile and run

icon_view

Clearing out old icons

Under iPhone Simulator menu select Reset Content and Settings:
delete_icons