P5js-WebSerial
From Digipool-Wiki
Contents
P5js-WebSerial
This code receives the value of A0 and displays it on the screen.
- Make sure to turn on WebSerial API in Chrome to connect (Arduino)
- Use the Basics/AnalogReadSerial example on the Arduino
- Click on the program window to establish the serial connection
- If the connection is interrupted, the program must be restarted (reload)
Use this command to send data to the Arduino:
if (serialDevice) {
serialDevice.writeString("1");
serialDevice.writeString("\n");
}
P5JS Code
let baud = 9600;
let serialDevice;
let serialValue = 0;
let inString = "1";
let inStringList = "";
let serialOn = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(0);
noStroke();
fill(255, 127);
text(serialValue, 100, 100);
}
function mousePressed() {
if (!!serialDevice) {
if (serialOn == 0) {
serialOn = 1;
} else {
serialOn = 0;
}
return;
}
serialDevice = new SerialDevice(
baud,
(data) => serialRead(data),
(err) => serialError(err)
);
serialOn = 1;
}
function serialRead(data) {
console.log("serial data:", data);
inStringList = splitTokens(data, " ");
if (serialOn == 1) {
if (inStringList.length == 1) {
serialValue = int(inStringList[0]);
}
}
}
function serialError(err) {
print("Error:", err);
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="serial-device.js"></script>
<script src="sketch.js"></script>
</body>
</html>
serial-device.js Class
class SerialDevice {
constructor(baudRate = 115200, readCallback = null, errorCallback = null) {
this.baudRate = baudRate;
this.readCallback = readCallback;
this.errorCallback = errorCallback;
this.initSerial();
}
async initSerial() {
try {
this.port = await navigator.serial.requestPort(); // Request a port and open a connection.
await this.port.open({
baudrate: this.baudRate,
baudRate: this.baudRate,
}); // Wait for the port to open. Use new & old `baudrate` key for different browsers
console.log(this.port);
this.initialized = true;
} catch (err) {
if (this.errorCallback) this.errorCallback(err);
return;
}
// start reading input
this.startWriting();
this.startReading();
}
async startReading() {
// input from serial device
this.decoder = new TextDecoderStream();
let inputDone = this.port.readable.pipeTo(this.decoder.writable);
this.inputStream = this.decoder.readable;
this.reader = this.inputStream.getReader();
this.readLoop();
}
async readLoop() {
while (true) {
const { value, done } = await this.reader.read();
if (value) {
if (this.readCallback) this.readCallback(value);
}
if (done) {
console.log("[readLoop] DONE", done);
this.reader.releaseLock();
break;
}
}
}
async startWriting() {
// output to serial device
this.encoder = new TextEncoderStream();
this.outputDone = this.encoder.readable.pipeTo(this.port.writable);
this.writerString = this.encoder.writable.getWriter();
}
async writeString(data) {
if (this.port && this.port.writable) {
await this.writerString.write(data);
} else {
console.log("[SerialDevice can't write string]", data);
}
}
}