xxxxxxxxxx
34
// 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(500, 300);
// Instantiate our SerialPort object
serial = new p5.SerialPort();
serial.open("/dev/cu.usbmodem1411");
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
var output = map(mouseX,0,width,0,255);
serial.write(output);
}
function draw() {
background(255,255,255);
fill(0,0,0);
var data = map(latestData, 0, 1023, 0, height);
ellipse(mouseX, data, 50, 50);
text(data, 10, 10);
}