xxxxxxxxxx
74
// This code was taken from https://github.com/ITPNYU/physcomp/blob/master/Labs/P5SerialLabs/P5ReadSerial/readSerial/sketch.js
let serial; // variable to hold an instance of the serialport library
let portName = '/dev/tty.usbmodem142101'; // fill in your serial port name here
let xPos = 0;
let yPos = 0;
let isLedOn = false;
function setup() {
createCanvas(800, 600);
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
background(0);
}
function draw() {
fill(255);
noStroke();
ellipse(xPos, yPos, 10, 10);
}
// 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:
console.log(i + " " + portList[i]);
}
}
function serverConnected() {
console.log('connected to server.');
}
function portOpen() {
console.log('the serial port opened.')
}
function serialEvent() {
const inString = serial.readStringUntil('\r\n');
if (inString.length > 0) {
const sensors = split(inString, ','); // split the string on the commas
const leftPot = sensors[0];
const rightPot = sensors[1];
xPos = map(leftPot, 0, 1023, 0, width);
yPos = map(rightPot, 0, 1023, 0, height);
}
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function portClose() {
console.log('The serial port closed.');
}
function keyPressed() {
if (key === 'H' || key === 'L') { // if the user presses H or L
console.log(key);
serial.write(key); // send it out the serial port
}
}