xxxxxxxxxx
59
var serial; // variable to hold an instance of the serialport library
var portName = '/dev/cu.usbmodem1421';
var inData;
function setup() {
serial = new p5.SerialPort(); // make a new instance of the serialport library
serial.on('list', printList); // set a callback function for the serialport list event
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
serial.list(); // list the serial ports
serial.open(portName); // open a serial port
}
function draw() {
background(220);
}
//Read a byte as ASCII:
function serialEvent() {
print("I got something:");
var inString = serial.readStringUntil('\r\n');
if (inString.length > 0 ) {
print(inString);
}
}
// get the list of ports:
function printList(portList) {
//bonus points - auto detect which port is the arduino
// portList is an array of serial port names
for (var i = 0; i < portList.length; i++) {
// Display the list the console:
console.log(i + portList[i]);
}
}
function serverConnected() {
console.log('connected to server.');
}
function portOpen() {
console.log('The serial port opened.')
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function portClose() {
console.log('The serial port closed.');
}