xxxxxxxxxx
88
// Ball simulation variables
let ballVelocity;
let ballGravity;
let ballPosition;
let ballAcceleration;
let ballWind;
let ballDrag = 0.99;
let ballMass = 50;
// Arduino communication variables
let arduinoWindSensorValue = 0;
let arduinoLedOn = 0;
function setup() {
createCanvas(400, 400);
ballPosition = createVector(width/2, 0);
ballVelocity = createVector(0,0);
ballAcceleration = createVector(0,0);
ballGravity = createVector(0, 0.5*ballMass);
ballWind = createVector(0,0);
}
function draw() {
background(0);
fill(255);
if (!serialActive) {text("Press Space Bar to select Serial Port", width/4, 30); }
else {text("Connected!", 165, 30); }
fill("#39FF14");
applyForce(ballWind);
applyForce(ballGravity);
ballVelocity.add(ballAcceleration);
ballVelocity.mult(ballDrag);
ballPosition.add(ballVelocity);
ballAcceleration.mult(0);
ellipse(ballPosition.x,ballPosition.y,ballMass,ballMass);
if (ballPosition.y > height-ballMass/2) {
ballVelocity.y *= -0.9; // A little dampening when hitting the bottom
ballPosition.y = height-ballMass/2;
arduinoLedOn = 1; //If the ball makes contact with the ground, the LED will be ON
}
else {arduinoLedOn = 0;} //Else the LED will be OFF
//If the arduinoWindSensorValue value from the Arduino that was mapped is greater than 0, then it will move the ball to the right
if(arduinoWindSensorValue > 0) {
ballWind.x = 0.5;
}
//Else if the arduinoWindSensorValue value from the Arduino is less than 0, it will move the ball to the left
else if(arduinoWindSensorValue < 0) {
ballWind.x = -0.5;
}
//If it's 0, aka no wind, then it will just keep the ball where it is, no wind.
else {
ballWind.x = 0;
}
}
function applyForce(force){
// Newton's 2nd law: F = M * A
// or A = F / M
let f = p5.Vector.div(force, ballMass);
ballAcceleration.add(f);
}
function keyPressed(){
if (key == "m"){
ballMass=random(15,80);
ballPosition.y=-ballMass;
ballVelocity.mult(0);
}
if(key == " ") {
setUpSerial();
}
}
function readSerial(data) {
if(data != null) {
//Sends the arduinoLedOn information to the Arduino
let sendToArduino = arduinoLedOn + "\n";
writeSerial(sendToArduino);
//Reads the arduinoWindSensorValue values from the Arduino and maps its value to either -1 or 1 to correspond to wind direction.
arduinoWindSensorValue = map(data, 0, 1023, -1 , 1);
}
}