Lab 4 - FSR and Recursive Trees

stephen.backer's picture

I've used my Arduino serial output to control the branching angle of a recursive tree in Processing. 

 

Materials:  Arduino, resistors, FSR

 

Arduino Code: 


int sensorPin = 2;  // select the input pin for the sensor
int val = 0;        // variable to store the value coming from the sensor

void setup() {
   Serial.begin(9600);
}
 
  // send value from Arduino sensor to Processing via the serial port.  

void loop() {
  val = analogRead(sensorPin); // read the value from the sensor, 0-1023
  Serial.println(val/4);       // writing the value to the PC via serial connection
  delay(50);                   // rest a little...
}

Processing Code: 

/**
 * Recursive Tree
 * Edited by Stephen Backer 9.27.11
 *
 * Renders a simple tree-like structure via recursion.
 * The branching angle is calculated as a function of
 * the horizontal mouse location. Move the mouse left
 * and right to change the angle.
 */
 
import processing.serial.*;
          // Change this to the portname your Arduino board
String portname = "/dev/tty.usbmodem621"; // or "COM5"
Serial port;
String buf="";
int cr = 13;  // ASCII return   == 13
int lf = 10;  // ASCII linefeed == 10



 
float theta;   

void setup() {
  size(640, 360);
  smooth();
 
 
}

void draw() {
  background(0);
  frameRate(30);
  stroke(255);
  // Let's pick an angle 0 to 90 degrees based on the mouse position
  float a = (int " " / (float) width) * 90f;
  // Convert it to radians
  theta = radians(a);
  // Start the tree from the bottom of the screen
  translate(width/2,height);
  // Draw a line 120 pixels
  line(0,0,0,-120);
  // Move to the end of that line
  translate(0,-120);
  // Start the recursive branching!
  branch(120);

}

void branch(float h) {
  // Each branch will be 2/3rds the size of the previous one
  h *= 0.66;
 
  // All recursive functions must have an exit condition!!!!
  // Here, ours is when the length of the branch is 2 pixels or less
  if (h > 2) {
    pushMatrix();    // Save the current state of transformation (i.e. where are we now)
    rotate(theta);   // Rotate by theta
    line(0, 0, 0, -h);  // Draw the branch
    translate(0, -h); // Move to the end of the branch
    branch(h);       // Ok, now call myself to draw two new branches!!
    popMatrix();     // Whenever we get back here, we "pop" in order to restore the previous matrix state
    
    // Repeat the same thing, only branch off to the "left" this time!
    pushMatrix();
    rotate(-theta);
    line(0, 0, 0, -h);
    translate(0, -h);
    branch(h);
    popMatrix();
  }
}

// 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);
     }
}

Arduino with FSR
0
Your rating: None