xxxxxxxxxx
70
// first I downloaded an app to help p5js access serial port from here: https://github.com/p5-serial/p5.serialcontrol/releases
let serial;
let latestData = "waiting for data";
function setup() {
createCanvas(500,500);
serial = new p5.SerialPort();
serial.list();
serial.open("/dev/tty.usbmodem2101");
serial.on('connected', serverConnected);
serial.on('list', gotList);
serial.on('data', gotData);
serial.onError(gotError);
serial.onOpen(gotOpen);
serial.on('close', gotClose);
}
// initial connection!
function serverConnected() {
print("Connected to Server");
}
function gotList(thelist) {
print("List of Serial Ports:");
// theList is an array of their names
for (let i = 0; i < thelist.length; i++) {
// Display in the console
print(i + " " + thelist[i]);
}
}
// connection to our device
function gotOpen() {
print("Serial Port is Open");
}
function gotClose(){
print("Serial Port is Closed");
latestData = "Serial Port is Closed";
}
function gotError(theerror) {
print(theerror);
}
// data from the serial port
function gotData() {
let currentString = serial.readLine();
trim(currentString);
if (!currentString) return;
console.log(currentString);
latestData = currentString;
}
function gotRawData(thedata) {
print("gotRawData" + thedata);
}
// drawing our ellipse + background
function draw() {
background(0);
fill(0);
stroke(188, 117, 255);
strokeWeight(15);
if (serial.available() > 0) {
let data = serial.read();
ellipse(data,250,100,100);
}
}