xxxxxxxxxx
104
/*
Make LED light up when ball bounces. Control wind from analog sensor.
Arduino code:
https://github.com/vsharkovski/nyuad-coursework/blob/main/introim/arduino/ball-wind/ball-wind.ino
*/
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
// Last ball bounce frame, and how many frames to send "bouncing"
// signal to Arduino.
let lastBallBounceFrame = -100;
let bounceFrames = 10;
let isBouncing = 0;
function setup() {
createCanvas(640, 360);
stroke(0);
textSize(18);
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);
fill(0);
noStroke();
if (!serialActive) {
text("Press Enter to select Serial Port", 20, 30);
return;
}
text("Connected", 20, 30);
// Determine whether currently bouncing.
isBouncing = lastBallBounceFrame + bounceFrames > frameCount ? 1 : 0;
applyForce(wind);
applyForce(gravity);
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
fill(100);
ellipse(position.x, position.y, mass, mass);
if (position.y > height - mass / 2) {
// Bouncing.
velocity.y *= -0.9; // A little dampening when hitting the bottom
position.y = height - mass / 2;
lastBallBounceFrame = frameCount;
}
}
function readSerial(data) {
if (data != null) {
// Read from Arduino.
// Make sure there is actually a message. Split the message.
let fromArduino = split(trim(data), ",");
if (fromArduino.length == 1) {
let potPosition = int(fromArduino[0]);
// Set wind based on sensor position.
wind.x = map(potPosition, 0, 1023, -3, 3);
}
// Send to Arduino whether currently bouncing.
let sendToArduino = `${isBouncing}\n`;
writeSerial(sendToArduino);
}
}
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 == ENTER) {
setUpSerial();
} else if (key == " ") {
mass = random(15, 80);
position.y = -mass;
position.x = width / 2;
velocity.mult(0);
}
}