xxxxxxxxxx
130
let rVal = 0; // red value
let alpha = 255; // background transparency
let left = 0;
let right = 0;
//gravity wind
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
function setup() {
textSize(18);
createCanvas(640, 360);
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);
// alpha is the second value in the string that Arduino sends, which is the value from the potentiometer
//the potentiometer goes from 0 to 1023 and color goes from 0 to 255, so it is good to use the map function
fill(220);
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;
}
console.log(position.y);
//send value to "left" LED in arduino
// depending on y-position of ball
// if y-position is greater than 330, light up the LED
if(position.y >= 330){
left = 1;
}
// if y-position is greater than 335, turn off the LED
if(position.y <= 335){
left = 0;
}
if (!serialActive) {
fill(0)
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
//control wind with potentiometer
wind.x = map(alpha, 0, 1023, -1, 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() {
// set up connection with p5:
if (key == " ") {
setUpSerial();
}
// if (keyCode == LEFT_ARROW) {
// wind.x = -1;
// }
// if (keyCode == RIGHT_ARROW) {
// wind.x = 1;
// }
if (key == " ") {
mass = random(15, 80);
position.y = -mass;
velocity.mult(0);
}
}
// This function will be called by the web-serial library
// with each new *line* of data. The serial library reads
// the data until the newline and then gives it to us through
// this callback function
function readSerial(data) {
////////////////////////////////////
//READ FROM ARDUINO HERE
////////////////////////////////////
//if there is data, proceed to read
if (data != null) {
// create array to store values from Arduino
let fromArduino = split(trim(data), ",");
// if the right length, then proceed
if (fromArduino.length == 2) {
// only store values here
// do everything with those values in the main draw loop
// converting values from from Arduino array into numbers. values from Arduino come as characters
rVal = int(fromArduino[0]);
alpha = int(fromArduino[1]);
}
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
let sendToArduino = left + "," + right + "\n";
writeSerial(sendToArduino);
}
}