xxxxxxxxxx
106
const serial = new p5.WebSerial();
let portButton;
let inData, inData2;
let currentColor;
function setup() {
createCanvas(800, 600);
allSerialStuff();
currentColor = 'black'; // Initial color for normal state
}
function draw() {
background(220);
// Map sensor values to canvas dimensions
let xPosition = map(inData, 0, 1023, 0, width);
let yPosition = map(inData2, 0, 1023, 0, height);
// Check sensor conditions and update color
if (inData <= 100 && inData2 > 1300) {
// Create gradient color for happy state
for (let i = 0; i <= height; i++) {
let r = map(i, 0, height, 255, 255); // Red component
let g = map(i, 0, height, 165, 255); // Gradation from orange to yellow
let b = 0; // No blue component
stroke(r, g, b);
line(0, i, width, i); // Draw gradient line
}
} else {
// Set black color for normal state
fill('black');
rect(0, 0, width, height);
}
// Display sensor values
fill(255); // White text for better visibility
textSize(16);
text(`Distance: ${inData}`, 10, 20);
text(`Pressure: ${inData2}`, 10, 40);
// Draw a small circle representing sensor values
fill(0, 0, 255);
ellipse(xPosition, yPosition, 15, 15);
}
function serialEvent() {
let stringFromSerial = serial.readLine();
if (stringFromSerial) {
let trimmedString = trim(stringFromSerial);
let myArray = split(trimmedString, ",");
inData = Number(myArray[0]); // Distance (ultrasonic sensor)
inData2 = Number(myArray[1]); // Pressure
}
}
function allSerialStuff() {
if (!navigator.serial) {
alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
}
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);
}
function makePortButton() {
portButton = createButton("choose port");
portButton.position(10, 10);
portButton.mousePressed(choosePort);
}
function choosePort() {
if (portButton) portButton.show();
serial.requestPort();
}
function openPort() {
serial.open().then(initiateSerial);
function initiateSerial() {
console.log("port open");
}
if (portButton) portButton.hide();
}
function portError(err) {
alert("Serial port error: " + err);
}
function portConnect() {
console.log("port connected");
serial.getPorts();
}
function portDisconnect() {
serial.close();
console.log("port disconnected");
}
function closePort() {
serial.close();
}