xxxxxxxxxx
102
// Graphs incoming serial data (single value)
//
// See also:
// https://editor.p5js.org/jonfroehlich/sketches/Szs_sh4qI
//
// By Jon E. Froehlich
// @jonfroehlich
// http://makeabilitylab.io/
//
let pHtmlMsg;
let serialOptions = { baudRate: 115200 };
let serial;
let curSerialVal = 0; // should be between 0 and 1
let currentXPos = 0;
function setup() {
createCanvas(400, 400);
// Setup Web Serial using serial.js
serial = new Serial();
serial.on(SerialEvents.CONNECTION_OPENED, onSerialConnectionOpened);
serial.on(SerialEvents.CONNECTION_CLOSED, onSerialConnectionClosed);
serial.on(SerialEvents.DATA_RECEIVED, onSerialDataReceived);
serial.on(SerialEvents.ERROR_OCCURRED, onSerialErrorOccurred);
// If we have previously approved ports, attempt to connect with them
serial.autoConnectAndOpenPreviouslyApprovedPort(serialOptions);
// Add in a lil <p> element to provide messages. This is optional
pHtmlMsg = createP("Click anywhere on this page to open the serial connection dialog");
pHtmlMsg.style('color', 'deeppink');
bgColor = color(100);
stroke("white");
}
function draw() {
// Check if current x position is off graph; if so. Clear!
if(currentXPos > width || currentXPos == 0){
currentXPos = 0;
background(100);
}
const yStart = height;
const yLineHeight = curSerialVal * height;
const yEnd = yStart - yLineHeight;
line(currentXPos, yStart, currentXPos, yEnd);
currentXPos++;
}
/**
* Callback function serial.js when new web serial data is received
*
* @param {*} eventSender
* @param {String} newData new data received over serial
*/
function onSerialDataReceived(eventSender, newData) {
console.log("onSerialDataReceived", newData);
pHtmlMsg.html("onSerialDataReceived: " + newData);
curSerialVal = parseFloat(newData);
}
/**
* Callback function by serial.js when there is an error on web serial
*
* @param {} eventSender
*/
function onSerialErrorOccurred(eventSender, error) {
console.log("onSerialErrorOccurred", error);
pHtmlMsg.html(error);
}
/**
* Callback function by serial.js when web serial connection is opened
*
* @param {} eventSender
*/
function onSerialConnectionOpened(eventSender) {
console.log("onSerialConnectionOpened");
pHtmlMsg.html("Serial connection opened successfully");
}
/**
* Callback function by serial.js when web serial connection is closed
*
* @param {} eventSender
*/
function onSerialConnectionClosed(eventSender) {
console.log("onSerialConnectionClosed");
pHtmlMsg.html("onSerialConnectionClosed");
}
/**
* Called automatically by the browser through p5.js when mouse clicked
*/
function mouseClicked() {
if (!serial.isOpen()) {
serial.connectAndOpen(null, serialOptions);
}
}