xxxxxxxxxx
113
let port;
let writer;
let reader;
let ledState = false;
let brightnessSlider;
let toggleButton;
let portButton;
let sensorValue = 0;
async function setup() {
createCanvas(400, 300).parent("ui");
// Check if Web Serial is supported
if (!("serial" in navigator)) {
alert("Web Serial API not supported. Please use Chrome or Edge.");
return;
}
// Create UI elements
brightnessSlider = createSlider(0, 255, 255);
brightnessSlider.position(10, 10);
brightnessSlider.input(sendBrightness);
toggleButton = createButton("Toggle LED");
toggleButton.position(10, 50);
toggleButton.mousePressed(toggleLED);
portButton = createButton("Connect to Arduino");
portButton.position(10, 90);
portButton.mousePressed(connectToArduino);
}
async function connectToArduino() {
try {
port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
writer = port.writable.getWriter();
reader = port.readable.getReader();
console.log("Connected to Arduino!");
portButton.html("Connected");
portButton.attribute("disabled", "");
// Start reading loop
readLoop();
} catch (error) {
console.error("Error connecting to Arduino:", error);
}
}
async function readLoop() {
while (true) {
try {
const { value, done } = await reader.read();
if (done) {
reader.releaseLock();
break;
}
// Parse incoming data
const data = new TextDecoder().decode(value);
const lines = data.split('\n');
for (let line of lines) {
line = line.trim();
if (line.startsWith('S:')) { // Sensor data
sensorValue = parseInt(line.substring(2));
} else if (line.startsWith('L:')) { // LED state
ledState = line.substring(2) === '1';
}
}
} catch (error) {
console.error("Error reading data:", error);
break;
}
}
}
async function sendBrightness() {
if (!writer) return;
try {
const brightness = brightnessSlider.value();
const data = new TextEncoder().encode(`B${brightness}\n`);
await writer.write(data);
} catch (error) {
console.error("Error sending brightness:", error);
}
}
async function toggleLED() {
if (!writer) return;
try {
ledState = !ledState;
const data = new TextEncoder().encode(`T${ledState ? 1 : 0}\n`);
await writer.write(data);
} catch (error) {
console.error("Error toggling LED:", error);
}
}
function draw() {
background(240);
textSize(16);
fill(0);
text(`LED is ${ledState ? "ON" : "OFF"}`, 10, 130);
text(`Brightness: ${brightnessSlider.value()}`, 10, 160);
text(`LDR Sensor Value: ${sensorValue}`, 10, 190);
// Visual representation of sensor value
noStroke();
fill(map(sensorValue, 0, 1023, 255, 0));
rect(10, 210, 200, 20);
}