You have to add some code to index.html in order for editor to recognize Serial port:
<script language="javascript" type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.serialport.js"></script>
There is also an app called p5.serialcontrol which will help format code for serial connections.
For example, the following code was generated for my system using the app p5.serialcontrol:
let serial;
let latestData = "waiting for data";
function setup() {
createCanvas(windowWidth, windowHeight);
serial = new p5.SerialPort();
serial.list();
serial.open('/dev/tty.usbmodem143301');
serial.on('connected', serverConnected);
serial.on('list', gotList);
serial.on('data', gotData);
serial.on('error', gotError);
serial.on('open', gotOpen);
serial.on('close', gotClose);
}
function serverConnected() {
print("Connected to Server");
}
function gotList(thelist) {
print("List of Serial Ports:");
for (let i = 0; i < thelist.length; i++) {
print(i + " " + thelist[i]);
}
}
function gotOpen() {
print("Serial Port is Open");
}
function gotClose(){
print("Serial Port is Closed");
latestData = "Serial Port is Closed";
}
function gotError(theerror) {
print(theerror);
}
function gotData() {
let currentString = serial.readLine();
trim(currentString);
if (!currentString) return;
console.log(currentString);
latestData = currentString;
}
function draw() {
background(255,255,255);
fill(0,0,0);
text(latestData, 10, 10);
// Polling method
/*
if (serial.available() > 0) {
let data = serial.read();
ellipse(50,50,data,data);
}
*/
}
I was able to connect to an Arduino UNO and successfully ran this code:
unsigned long LoopTimer = 0;
byte outputValue = 0;
const int LoopTime50 = 50;
const int LoopTime100 = 100;
const int LoopTime20000 = 20000;
void setup() {
Serial.begin(9600);
}
void loop() {
if (micros() >= LoopTimer) {
LoopTimer += LoopTime100;
outputValue += 8;
Serial.println(outputValue);
}
}
You will have to change the serial port name for your system. You should be able to download the app here: https://github.com/p5-serial . Use this app to open the serial port also.