xxxxxxxxxx
99
/*
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-12-2021
*/
let serial; // variable for serial object
var portSelector; // a select menu for the port list
let r = 0;
let outgoing = 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(r, 123, 25);
outgoing = round(map(mouseX, 0, width, 0, 179));
text("servo position: " + outgoing, 10, 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) {
console.log(currentString);
r = round(map(currentString, 0, 1023, 0, 255));
serial.write(outgoing);
}
}
// get the list of ports:
function gotList(portList) {
// make a select menu and position it:
portSelector = createSelect();
portSelector.position(10, 10);
// 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]);
// add item to the select menu:
portSelector.option(portList[i]);
}
// set a handler for when a port is selected from the menu:
portSelector.changed(openPort);
}
function openPort() {
var thisPort = portSelector.value();
if (thisPort != null) {
serial.open(thisPort);
serial.write('x');
}
portSelector.hide();
}
// We are connected and ready to go
function serverConnected() {
console.log("We are connected!");
}
// Connected to our serial device
function gotOpen() {
console.log("Serial Port is open!");
}
// disconnected from our serial device
function gotClose() {
console.log("Serial Port is closed!");
}
// Ut oh, here is an error, let's log it
function gotError(theerror) {
console.log(theerror);
}