xxxxxxxxxx
103
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let heightOfBall = 0;
function setup() {
createCanvas(640, 360); // Create a canvas of 800x400 pixels
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(215);
fill(0);
if (!serialActive) {
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);
ellipse(position.x,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;
}
}
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 keyPressed() {
if (key == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
}
if (key=='s'){
mass=random(15,80);
position.y=-mass;
velocity.mult(0);
}
}
// this callback function
function readSerial(data) {
////////////////////////////////////
//READ FROM ARDUINO HERE
////////////////////////////////////
if (data != null) {
// make sure there is actually a message
console.log(data);
console.log("fromArduino");
let fromArduino = split(trim(data), ",");
// if the right length, then proceed
console.log(fromArduino);
if (fromArduino.length == 2) {
console.log("data is here ")
console.log(data);
//wind.x += data;
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
console.log("position.y");
console.log(position.y);
if (position.y + mass/2 == height)
{
heightOfBall =0;
}
else{
heightOfBall = 1;
}
console.log("height of ball = ");
console.log(heightOfBall);
let sendToArduino = heightOfBall + "\n";
writeSerial(sendToArduino);
}
}
}