xxxxxxxxxx
103
//exercise 3 p5js
let velocity;
let gravity;
let position;
let acceleration;
let breeze;
let drag = 0.99;
let mass = 50;
let heightOfBall = 0;
function setup() {
createCanvas(640, 360);
noFill();
position = createVector(width/2, 0);
velocity = createVector(0,0);
acceleration = createVector(0,0);
gravity = createVector(0, 0.5*mass);
breeze = createVector(0,0);
}
function draw() {
background(215);
fill(0);
if (!serialActive) {
text("Press the space bar to select the serial Port", 20, 30);
}
else
{
text("Arduino is connected! Press b to jump.", 20, 30);
applyForce(breeze);
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;
heightOfBall = 0;
}
else {
heightOfBall = 1;
}
}
}
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();
}
else if (key=='b'){
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
let fromArduino = split(trim(data), ",");
// if the right length, then proceed
if (fromArduino.length == 1) {
let sensorVal = int(fromArduino[0]);
//for values less than 400,wind blows to right
if (sensorVal < 400){
breeze.x=1
}
//if value between 400 and 500, wind stops so ball stops
else if(sensorVal >= 400 && sensorVal < 500){
breeze.x = 0
}
//if value greater than 500, wind blows to left
else {
breeze.x = -1
}
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
}
//height of ball sent to arduino to check if ball on floor or not
let sendToArduino = heightOfBall + "\n";
writeSerial(sendToArduino);
}
}