User login

Powered by Drupal, an open source content management system

Theory and Practice of Tangible User Interfaces

Force Sensitive Volume Control

Submitted by jonyen on Thu, 10/02/2008 - 04:25

Assignment: Sensing PART II: Force sensors and photocells

Collaborators:

Assignment: Sensing PART II: Force sensors and photocells

Description:

Used an FSR (Force Sensitive Resistor) as an input to control the volume in Mac OS X. I found some code online that would enable me to control AppleScript from Processing. Then I integrated that with the serial input from the Arduino board and used the values from the FSR to adjust the volume control. When there is no input (value = 0), then the volume does not get changed. Otherwise the volume will change depending on how hard you press on the control.

Components:

  • 10K resistor
  • FSR
  • Wires
  • Apple Computer
Code: 
import com.apple.cocoa.foundation.*; 
import processing.serial.*; 
 
String portname = "/dev/tty.usbserial-A7006x13"; // or "COM5"
Serial port;
String buf="";
int cr = 13;  // ASCII return   == 13
int lf = 10;  // ASCII linefeed == 10
PFont fontA;
int currentVolume = 0;
int maxSoFar = 0;
 
void setup() { 
  size(400,400);
  port = new Serial(this, portname, 9600);  
  fontA = loadFont("Ziggurat-HTF-Black-32.vlw");
  textFont(fontA, 32);
} 
 
void keyPressed() { 
  switch(key) { 
    case('p'):iTunes("play");break; 
    case('s'):iTunes("pause");break; 
  } 
} 
 
void draw() {
  background(176);
  fill(0);
  text("Current volume: " + currentVolume, 10, 36);
} 
 
 
void iTunes(String theCommand) { 
  String script = "tell application \"iTunes\""+"\n" + theCommand + "\n" + "end tell"; 
  executeScript(script); 
} 

void changeVolume(int volume) {
  println("changing volume " + volume);
  if (volume != 0) {
    currentVolume = volume;
    String script = "set volume output volume " + volume;
    executeScript(script);
    
  }
}

   
void executeScript(String script) { 
  NSAppleScript myScript = new NSAppleScript(script); 
  NSMutableDictionary errors = new NSMutableDictionary(); 
  myScript.execute(errors);   
} 

// called whenever serial data arrives
void serialEvent(Serial p) {
  int c = port.read();
  
  if (c != lf && c != cr) {
    buf += char(c);
  }
  if (c == lf) {
    int val = int(buf);
    println("val="+val); 
    buf = "";
    if (val == 0) {
       maxSoFar = 0;
    }
    if (val != 0 && val > maxSoFar) {
      maxSoFar = val;
      changeVolume(val / 10);
    }
  }
}