xxxxxxxxxx
82
let video; // Variable to hold the video
let serial; // Instance of the p5.WebSerial library
let inData = ''; // Incoming serial data
let isPlaying = false; // Flag to track if the video is currently playing
function setup() {
createCanvas(400, 300); // Create the canvas
// Load the video (replace with your actual video file path)
video = createVideo('ezyZip (1).mp4');
video.hide(); // Hide the video element until it plays
// Check if WebSerial is supported in this browser
if (!navigator.serial) {
alert("WebSerial is not supported in this browser. Try using Chrome or Edge.");
return;
}
// Initialize WebSerial
serial = new p5.WebSerial();
// Get the available serial ports and open one
serial.getPorts();
serial.on("noport", makePortButton);
serial.on("portavailable", openPort);
serial.on("requesterror", portError);
serial.on("data", serialEvent); // Handle incoming serial data
}
function draw() {
background(220);
// Display the video on the canvas if it's playing
if (video) {
image(video, 0, 0, width, height);
}
}
// Create a button to select the serial port if none is available
function makePortButton() {
let portButton = createButton("Choose Serial Port");
portButton.position(10, 10);
portButton.mousePressed(() => serial.requestPort());
}
// Open the serial port when available
function openPort() {
serial.open(); // Open the selected serial port
}
// Handle incoming serial data
function serialEvent() {
let data = serial.readLine(); // Read incoming data as a string
if (data) {
inData = data.trim(); // Remove any whitespace from the data
// Check if the message is 'PLAY_VIDEO' and video is not already playing
if (inData === "PLAY_VIDEO" && !isPlaying) {
playVideo(); // Trigger video playback
}
}
}
// Play the video for 10 seconds, then stop it
function playVideo() {
isPlaying = true; // Set flag to stop further detection
video.play(); // Play the video
console.log("Video started");
// Stop the video after 10 seconds and reset the flag
setTimeout(() => {
video.stop(); // Stop the video
isPlaying = false; // Allow new detection after video ends
console.log("Video ended, resuming detection.");
}, 10000); // Play for 10 seconds
}
// Handle serial port error
function portError(err) {
console.error("Serial port error: ", err);
}