xxxxxxxxxx
61
/*
Code adapted from p5 Serialport resources:
https://github.com/p5-serial/p5.serialport
https://itp.nyu.edu/physcomp/labs/labs-serial-communication/lab-serial-input-to-the-p5-js-ide/
by David Rios IMA 10-13-2021
*/
let serial; // variable for serial object
var portSelector; // a select menu for the port list
let c = 0;
let x = 0;
let y = 0;
let options = {
baud: 9600, // Serial baud Rate
};
function setup() {
createCanvas(windowWidth, windowHeight);
serial = new p5.SerialPort(options); // Create the serial object
let portlist = serial.list(); // get an array of available serial ports
// Register some callbacks
serial.on("connected", serverConnected); // print feedback on connection
serial.on("list", gotList); // print out list of available ports
serial.on("error", gotError); // print out any errors when they occur
serial.on("open", gotOpen); // print out feedback when the port is opened
serial.on("data", serialEvent); // callback for when p5 receives data from arduino
}
function draw() {
background(c);
ellipse(x, y, 50, 50)
// evenutally we will draw things with our sensors
}
function serialEvent() {
let currentString = serial.readStringUntil("\r\n");
// read incoming sensor info
// if we have info to read.
if (currentString) {
let sensors = split(currentString, ",");
console.log(sensors);
x = int(sensors[0]);
y = int(sensors[1]);
// c = int(currentString);
c = map(int(sensors[2]), 0, 1, 120, 255);
// console.log(c);
serial.write("x");
}
}