xxxxxxxxxx
68
var serial; // variable to hold an instance of the serialport library
var portName;
//var data = { "sensor1": -1, "sensor2": -1, "sensor3": -1};
var data;
var dataOK = false;
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('open', portOpen);
serial.on('connected', serverConnected); // callback for connecting to the server
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
createCanvas(400, 400);
}
// get the list of ports, standard version
function printList(portList) {
// 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 draw() {
background(255, 0, 200);
fill(255);
// console.log("Hi from the draw loop");
// console.log(data);
if (dataOK) {
text("Sensor1 is " + data.sensor1, 100, 100);
text("Sensor2 is " + data.sensor2, 100, 150);
text("Sensor3 is " + data.sensor3, 100, 200);
}
}
function portOpen() {
console.log("--OPEN! Connected with " + portName);
}
function portClose() {
console.log('The serial port closed.');
}
function serverConnected() {
console.log('connected to server.');
}
function serialEvent() {
var inString = serial.readLine();
if (inString.length > 0) {
console.log(inString);
data = JSON.parse(inString);
console.log(data);
dataOK = true; //could check this
}
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function portClose() {
console.log('The serial port closed.');
}