xxxxxxxxxx
51
let left = 0; // True if mouse is clicked on left side of the screen
let right = 0; // True if mouse is clicked on right side of the screen
let xPos = 0;
let yPos = 0;
function setup() {
createCanvas(480, 480);
textSize(18);
}
function draw() {
background(0); // Clear the background with black color
// Display connection status
fill(255, 0, 255, map(alpha, 0, 1023, 0, 255)); // Transparency based on alpha
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
}
// Update left and right variables based on mouse click position
left = (mouseIsPressed && mouseX <= width / 2) ? 1 : 0;
right = (mouseIsPressed && mouseX > width / 2) ? 1 : 0;
// Draw an ellipse based on the distance from the Arduino
let eWidth = width / 5;
let eHeight = height / 8;
ellipse(map(xPos, 0, 1023, 0, width), map(yPos, 0, 1023, 0, height), eWidth, eHeight);
}
function keyPressed() {
if (key === " ") {
setUpSerial(); // Initiate serial connection when spacebar is pressed
}
}
function readSerial(data) {
if (data) {
// Parse the incoming data and update the distance
let fromArduino = split(trim(data), ",");
xPos = int(fromArduino[0]); // Ensure distance is an integer value
yPos = int(fromArduino[1]); // Ensure distance is an integer value
// Send control values (left, right) to Arduino
let sendToArduino = `${left},${right}\n`;
console.log(data, sendToArduino); // Log incoming data and what is being sent
writeSerial(sendToArduino); // Send control data to Arduino
}
}