xxxxxxxxxx
72
let Distance = 0; // tracks the new shape fraction off serial
let serial; // the Serial object
let pHtmlMsg; // used for displaying messages via html (optional)
let serialOptions = { baudRate: 9600 };
function setup() {
createCanvas(500, 500);
colorMode(HSB, 360, 100, 100);
rectMode(CENTER);
// 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");
}
function onSerialErrorOccurred(eventSender, error) {
console.log("onSerialErrorOccurred", error);
pHtmlMsg.html(error);
}
function onSerialConnectionOpened(eventSender) {
console.log("onSerialConnectionOpened");
pHtmlMsg.html("Serial connection opened successfully");
}
function onSerialConnectionClosed(eventSender) {
console.log("onSerialConnectionClosed");
pHtmlMsg.html("onSerialConnectionClosed");
}
function onSerialDataReceived(eventSender, newData) {
console.log("onSerialDataReceived", newData);
pHtmlMsg.html("onSerialDataReceived: " + newData);
// Parse the incoming value as a float
Distance = parseFloat(newData);
}
function draw() {
background(0);
noStroke();
// IF I USE THE MOUSEX IN THIS WAY IT WORKS
//let colorx = mouseX;
//fill(colorx, 100, 100);
// I added a map function here. Try using newData instead of Distance if this does not work
//let color1 = int(map(Distance, 0, 350, 0, 360));
fill(int(Distance), 100, 100);
//fill(Distance, 100, 100);
rect(260, 260, 200, 200);
}
/**
* Called automatically by the browser through p5.js when mouse clicked
*/
function mouseClicked() {
if (!serial.isOpen()) {
serial.connectAndOpen(null, serialOptions);
}
}