xxxxxxxxxx
53
var serial; // variable to hold an instance of the serialport library
var portName = '/dev/cu.thisWontWorkEver'; // fill in your serial port name here
var inData;
function setup() {
createCanvas(640, 480);
background(0x08, 0x16, 0x40);
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 NOTE: I like to chain open from list, so I can decide which port is the arduino
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
}
// get the list of ports:
function printList(portList) {
// portList is an array of serial port names
for (var i = 0; i < portList.length; i++) {
// Display the list the console:
println(i + " " + portList[i]);
if (portList[i].indexOf("COM3") != -1) { //indexOf gives the starting position of a substring within a longer string, and returns -1 if not found.
portName = portList[i];
console.log("Will attempt to open Arduino on " + portName + " for serial connection");
}
}
serial.open(portName); //NOTE: here is my open command.
}
function serialEvent() {
inData = Number(serial.read());
console.log("Got serial data: " + inData);
}
function draw() {
//background(0);
// fill(255);
// text("sensor value: " + inData, 30, 30);
//graphData(inData);
}
function serialError(err) { println('Something went wrong with the serial port. ' + err); }
function portClose() { println('The serial port closed.'); }
function serverConnected() { println('connected to server.'); }
function portOpen() { println('the serial port opened.') }