xxxxxxxxxx
110
let velocity;
let gravity;
let position;
let acceleration;
let drag = 0.99;
let mass = 50;
let wind;
let windValue = 0; // Wind force value from Arduino
let ballDropped = false; // Controls when the ball starts dropping
let ledOn = false; // Tracks whether the LED is on
function setup() {
createCanvas(640, 360);
noFill();
textSize(18);
// Initialize motion vectors
position = createVector(width / 2, 0);
velocity = createVector(0, 0);
acceleration = createVector(0, 0);
gravity = createVector(0, 0.5 * mass);
wind = createVector(0, 0);
}
function draw() {
background(255);
fill(0); // Ensure text is visible
if (!ballDropped) {
// If the ball hasn't been dropped yet, display instructions
text("Press D to drop the ball", 20, 30);
text("Press Space Bar to select Serial Port", 20, 50);
return; // Exit the draw loop early until the ball is dropped
}
if (serialActive) {
text("Connected", 20, 30);
text(`Wind Speed: ${windValue}`, 20, 50); // Display wind speed
} else {
text("Serial Port Not Connected", 20, 30);
}
// Update wind vector based on windValue
wind.set(windValue, 0);
// Apply forces
applyForce(gravity);
applyForce(wind);
// Update ball's motion
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
// Draw the ball
ellipse(position.x, position.y, mass, mass);
// Check for bouncing
if (position.y >= height - mass / 2) {
velocity.y *= -0.9; // Dampening effect
position.y = height - mass / 2;
// Turn on LED when the ball hits the floor
if (serialActive && !ledOn) {
writeSerial("1,0\n"); // Signal to turn on LED
ledOn = true; // Mark LED as on
}
} else if (ledOn) {
// Turn off LED when the ball is not on the floor
writeSerial("0,0\n"); // Signal to turn off LED
ledOn = false; // Mark LED as off
}
}
// Apply forces to the ball
function applyForce(force) {
let f = p5.Vector.div(force, mass);
acceleration.add(f);
}
// Key press to start the serial connection or drop the ball
function keyPressed() {
if (key == " ") {
setUpSerial();
}
if (key == "D" || key == "d") {
dropBall();
}
}
// Function to drop the ball
function dropBall() {
position.set(width / 2, 0);
velocity.set(0, 0);
mass = 50; // Randomize mass for variety
gravity = createVector(0, 0.5 * mass);
ballDropped = true;
}
// Read data from Arduino
function readSerial(data) {
if (data != null) {
let fromArduino = split(trim(data), ",");
if (fromArduino.length === 1) {
windValue = int(fromArduino[0]); // Update wind force from Arduino
}
}
}