xxxxxxxxxx
51
// Declare a "SerialPort" object
var serial;
var latestData = "waiting for data"; // you'll use this to write incoming data to the canvas
function setup() {
createCanvas(400, 400);
var angle = PI/4;
// Instantiate our SerialPort object
serial = new p5.SerialPort();
serial.open("/dev/cu.usbmodem1421");
serial.on('data', gotData);
}
// There is data available to work with from the serial port
function gotData() {
var currentString = serial.readLine(); // read the incoming string
//same as readStringUntil(‘\r\n’)
trim(currentString); // remove any trailing whitespace
if (!currentString) return; // if the string is empty, do no more
latestData = int(currentString); // save it for the draw method
console.log(latestData); // println the string
}
function draw() {
background(0);
fill(0,0,0);
stroke(255);
strokeWeight(2);
translate(200,height);
angle = map(latestData, 0, 1023, PI/4, 0);
branch(100);
}
function branch(len){
line(0,0,0,-len);
if(len>4){
push();
translate(0,-len);
rotate(angle);
branch(len*0.67);
pop();
push();
translate(0,-len);
rotate(-angle);
branch(len*0.67);
pop();
}
}