xxxxxxxxxx
119
let serial;
let portButton;
let ultrasonicState = "No";
let pressureState = "No detect";
let isConnected = false;
let gradientColor;
function setup() {
createCanvas(400, 450);
if (!("serial" in navigator)) {
alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
return;
}
serial = new p5.WebSerial();
serial.getPorts();
serial.on("noport", makePortButton);
serial.on("portavailable", openPort);
serial.on("requesterror", portError);
serial.on("data", serialEvent);
serial.on("close", makePortButton);
navigator.serial.addEventListener("connect", portConnect);
navigator.serial.addEventListener("disconnect", portDisconnect);
makePortButton();
gradientColor = createGraphics(width, height);
createGradient();
}
function draw() {
background(220);
if (ultrasonicState === "Yes") {
background(255, 165, 0); // Orange
} else if (pressureState === "detect") {
image(gradientColor, 0, 0);
}
fill(0);
textSize(16);
textAlign(LEFT, TOP);
text(`Ultrasonic: ${ultrasonicState}`, 10, 10);
text(`Pressure: ${pressureState}`, 10, 30);
text(`Connection Status: ${isConnected ? "Connected" : "Disconnected"}`, 10, 50);
}
function serialEvent() {
let stringFromSerial = serial.readStringUntil("\n");
if (stringFromSerial) {
stringFromSerial = stringFromSerial.trim();
if (stringFromSerial === "Yes") {
ultrasonicState = "Yes";
} else if (stringFromSerial === "No") {
ultrasonicState = "No";
} else if (stringFromSerial === "detect") {
pressureState = "detect";
} else if (stringFromSerial === "No detect") {
pressureState = "No detect";
}
}
}
function createGradient() {
gradientColor.background(220);
for (let y = 0; y < height; y++) {
let r = map(y, 0, height, 255, 0);
let b = map(y, 0, height, 0, 255);
gradientColor.stroke(r, 0, b);
gradientColor.line(0, y, width, y);
}
}
function makePortButton() {
portButton = createButton("choose port");
portButton.position(10, height - 30);
portButton.mousePressed(choosePort);
isConnected = false;
}
function choosePort() {
serial.requestPort();
}
function openPort() {
serial.open().then(initiateSerial);
function initiateSerial() {
console.log("port open");
isConnected = true;
//if (portButton) portButton.hide();
}
}
function portError(err) {
console.error("Serial port error: " + err);
isConnected = false;
}
function portConnect() {
console.log("port connected");
serial.getPorts();
isConnected = true;
}
function portDisconnect() {
console.log("port disconnected");
serial.close();
isConnected = false;
makePortButton();
}
function closePort() {
serial.close();
isConnected = false;
}