xxxxxxxxxx
110
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let pot;
let left = 0;
let right = 0;
let rcolor;
let gcolor;
let bcolor;
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);
wind = createVector(0, 0);
rcolor = random(0, 255);
gcolor = random(0, 255);
bcolor = random(0, 255);
}
function draw() {
background(255);
if (serialActive) {
applyForce(wind);
applyForce(gravity);
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
fill(rcolor, gcolor, bcolor);
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;
left = (left + 1) % 2;
if (left == 0) {
right = 1;
} else {
right = 0;
}
}
} else {
fill(255, 0, 255, 255);
text("Press Right Arrow to select Serial Port", 20, 30);
}
}
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 (keyCode == RIGHT_ARROW) {
// important to have in order to start the serial connection!!
setUpSerial();
}
if (key == " ") {
mass = random(15, 80);
position.y = -mass;
velocity.mult(0);
rcolor = random(0, 255);
gcolor = random(0, 255);
bcolor = random(0, 255);
left = 0;
right = 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 (data != null) {
// make sure there is actually a message
// split the message
let fromArduino = split(trim(data), ",");
// if the right length, then proceed
if (fromArduino.length == 1) {
// only store values here
// do everything with those values in the main draw loop
// We take the string we get from Arduino and explicitly
// convert it to a number by using int()
// e.g. "103" becomes 103
wind.x = map(float(fromArduino[0]), 0, 1023, 5, -5);
}
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
let sendToArduino = left + "," + right + "\n";
writeSerial(sendToArduino);
}
}