xxxxxxxxxx
89
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let LED_value;
function setup() {
createCanvas(840, 560);
noFill();
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);
if (!serialActive) {
fill(0,0,0);
textSize(20);
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
applyForce(wind);
applyForce(gravity);
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
if (position.x > mass/2 && (position.x) < width - mass/2){
ellipse(position.x,position.y,mass,mass);
}
else if (position.x < mass/2){
velocity.x *= -0.9;
position.x = mass / 2;
ellipse(mass/2,position.y,mass,mass);
}
else if (position.x > position.x - mass/2) {
velocity.x *= -0.9;
position.x = width - mass / 2;
ellipse(width - mass/2,position.y,mass,mass);
}
if (position.y > height-mass/2) {
velocity.y *= -0.9; // A little dampening when hitting the bottom
position.y = height-mass/2;
}
LED_value = (position.y == height - mass/2) ? 1: 0;
}
}
function keyPressed() {
if (key === " ") {
setUpSerial(); // Initiate serial connection when spacebar is pressed
}
if (key=='m'){ // mass
mass=random(15,80);
position.y=-mass;
velocity.mult(0);
}
}
function applyForce(force){
// Newton's 2nd law: F = M * A
// or A = F / M
let f = p5.Vector.div(force, mass);
acceleration.add(f);
}
function readSerial(data) {
if (data) {
let fromArduino = int(map(int(data), 0, 1023, -3, 3)); // Adjust the scale for smoother wind force
// Gradually adjust the wind.x force with lerp
let targetWindX = fromArduino * 0.5; // Scale down wind force for smoother effect
wind.x = lerp(wind.x, targetWindX, 0.1); // Smoothly adjust wind
let sendToArduino = `${LED_value}\n`;
console.log(fromArduino, sendToArduino);
writeSerial(sendToArduino); // Send control data to Arduino
}
}