xxxxxxxxxx
113
// This sketch demonstrates how to
//
// TODO:
//
// By Jon E. Froehlich
// http://makeabilitylab.io/
let pHtmlMsg;
let mapShapeTypeToShapeName = {
0: "Circle",
1: "Square",
2: "Triangle"
};
let curShapeType = 0;
const MIN_SHAPE_SIZE = 10; // minimum shape size in pixels
const MAX_SHAPE_MARGIN = 10; // when shape is at max size, the margin to edge of canvas
let maxShapeSize = -1; // the maximum shape size
let curShapeSize = 10; // the current shape size
let serialOptions = { baudRate: 115200 };
function setup() {
createCanvas(736, 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);
maxShapeSize = min(width, height) - MAX_SHAPE_MARGIN;
// 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");
}
/**
* 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");
}
/**
* 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);
}
/**
* Called automatically by p5js. Call frameRate(<num>) to change how often this
* function is called
*/
function draw() {
background(100);
fill(250);
noStroke();
const xCenter = width / 2;
const yCenter = height / 2;
circle(xCenter, yCenter, curShapeSize);
}
function mouseMoved(){
curShapeSize = map(mouseX, 0, width, MIN_SHAPE_SIZE, maxShapeSize);
curShapeSize = constrain(curShapeSize, MIN_SHAPE_SIZE, maxShapeSize);
}
// Comment this out for now
// function mouseClicked() {
// if (!serial.isOpen()) {
// serial.connectAndOpen(null, serialOptions);
// }
// }