xxxxxxxxxx
57
var serial;
var mcd = {};
var logData = false;
function setup() {
createCanvas(400, 400);
serial = new p5.SerialPort();
serial.on('list', printList);
//serial.on('connected', serverConnected); // callback for connecting to the server
//serial.on('open', portOpen); // callback for the port opening
serial.on('data', serialEvent); // callback for when new data arrives
serial.on('error', serialError); // callback for errors
//serial.on('close', portClose); // callback for the port closing
}
function serialEvent() {
var inString = serial.readStringUntil('\r\n');
// check to see that there's actually a string there:
if (inString.length > 0 ) {
//console.log(inString);
try {
mcd = JSON.parse(inString);
} catch (e) { console.log(e); }
if (logData) console.log(mcd);
}
}
function draw() {
background(220);
fill(mcd.red, mcd.green, mcd.blue);
ellipse(100, 100, mcd.radius, mcd.radius);
}
function printList(portList) {
for (var i=0; i<portList.length; i++) {
var p = portList[i];
if (p.indexOf('usbmodem') > -1) {
print(p + " looks like the Arduino serial port");
serial.open(p, {baudrate: 115200});
}
}
}
function serialError(err) {
println('Issue: ' + err);
}
function portClose() {
println('The serial port closed.');
}
function println(p) { print(p); }