xxxxxxxxxx
131
//This is a modified combination of Professor Sherwood's programs:
//https://editor.p5js.org/aaronsherwood/sketches/q2Pl77SWl
//https://editor.p5js.org/aaronsherwood/sketches/I7iQrNCul
//Ball Physics
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
//Variable for Checking Bounce
let bounce = 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);
wind = createVector(0,0);
}
function draw() {
background(255);
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;
bounce = 1;
} else{
bounce = 0;
}
if (!serialActive) {
print("Press Space Bar to select Serial Port");
} else {
print("Connected");
}
}
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==' '){
if (!serialActive){
setUpSerial();
}
mass = random(15,80);
position.x = 320;
position.y = -mass;
velocity.mult(0);
}
}
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
wind.x = fromArduino[0];
print(wind.x);
}
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
let sendToArduino = bounce + "\n";
writeSerial(sendToArduino);
print("Sent to Arduino: " + bounce);
}
}
//Arduino Code
/*
//Initialize Variables
int potentio = A2;
int led = 5;
int bounce = 0;
void setup() {
Serial.begin(9600);
pinMode(5, OUTPUT); //Set pin
digitalWrite(led, LOW);
// Starts connection
while (Serial.available() <= 0) {
Serial.println("0"); // Starting Message
delay(300);
}
}
void loop() {
// Wait for data from p5 before doing something
while (Serial.available()) {
bounce = Serial.parseInt();
if (Serial.read() == '\n') {
digitalWrite(led, bounce);
delay(1);
int potValue = analogRead(potentio);
delay(1);
if (potValue < 512){
Serial.println(-1);
} else {
Serial.println(1);
}
}
}
}
*/