xxxxxxxxxx
60
let serial; //name serial is arbitrary - this is just a variable at this point
let portName = "not set";
let inData;
function setup() {
serial = new p5.SerialPort();
serial.on('list', printList);
serial.on('open', portOpen);
serial.on('error', serialError);
serial.on('data', serialEvent); // callback for when new data arrives
serial.list();
console.log("Opening " + portName);
createCanvas(400, 400);
}
function draw() {
background(220);
}
//Once everything is set up and working, all the action happens here:
function serialEvent() {
console.log("Serial event");
var inString = serial.readLine();
// check to see that there's actually a string there:
if (inString.length > 0 ) {
// convert it to a number:
inData = Number(inString);
console.log(inString);
}
}
function printList(portList) {
print("Inside printList");
var candidatePort = "not set";
var foundPort = false;
for (var i = 0; i < portList.length; i++) {
// Display the list the console:
console.log(i + portList[i]);
if (portList[i].indexOf('usbmodem')>=0) {
console.log(portList[i] + " is probably the Arduino");
candidatePort = portList[i];
foundPort = true;
}
}
if (foundPort) {
console.log("From list, opening " + candidatePort);
serial.open(candidatePort);
}
}
function portOpen() {
console.log('The serial port opened.')
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}