xxxxxxxxxx
170
// Declaring Global Variables
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let WindLeft=0;
let WindRight=0;
function setup()
{
// Initialising Variables
createCanvas(windowWidth, windowHeight);
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, 255, 255);
if (!serialActive)
{ textSize(20);
fill(10, 10, 255);
textAlign(CENTER, CENTER);
text("Press 'Enter' key to select Serial Port", width / 2, 30);
}else
{
if(WindLeft>WindRight)
{
// Right Winds and Arraws to Indicate the wind direction
wind.x=1;
stroke(10);
strokeWeight(40);
line(100, height / 2, 300, height / 2);
triangle(290, height / 2 - 5, 300, height / 2, 290, height / 2 + 5);
}else
{
// Left Winds and Arraws to Indicate the wind direction
wind.x=-1;
stroke(10);
strokeWeight(40);
line(500, height / 2, 300, height / 2);
triangle(310, height / 2 - 5, 300, height / 2, 310, height / 2 + 5);
}
stroke(0);
strokeWeight(1);
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)
{
// A little dampening when hitting the bottom
velocity.y *= -0.9;
position.y = height-mass/2;
}
// Sending Data to Arduino When the Ball hits the Ground for LED Lighting
if(position.y+mass/2==height)
{
writeSerial(1+'\n');
}else
{
writeSerial(0+'\n');
}
}
}
// Function to Apply Force
function applyForce(force)
{
// Newton's 2nd law: F = M * A
// or A = F / M
let f = p5.Vector.div(force, mass);
acceleration.add(f);
}
// Keys controlling Serial Port selection and Random Balls generation
function keyPressed()
{
if (keyCode === ENTER)
{
setUpSerial();
}
if (key==' ')
{
mass=random(15,80);
position.y=-mass;
velocity.mult(0);
}
}
function windowResized()
{
resizeCanvas(windowWidth, windowHeight);
}
function readSerial(data)
{
let values = data.trim().split(",");
if (values.length === 2)
{
WindLeft = int(values[0]);
WindRight = int(values[1]);
}
console.log("WindLeft: "+WindLeft+" "+"WindRight: "+WindRight);
}
// Arduino Code can be found below
/*
// Setting Global Variables
const int ledPin1 = 9;
const int ledPin2 = 6;
int WindLeftPin=A0;
int WindRightPin=A1;
int brightness = 0;
void setup()
{
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
// Start serial communication
Serial.begin(9600);
}
void loop()
{if (Serial.available())
{
int WindLeft = analogRead(WindLeftPin);
int WindRight = analogRead(WindRightPin);
Serial.print(WindLeft);
Serial.print(",");
Serial.print(WindRight);
Serial.println();
int value = Serial.parseInt();
if (value == 0)
{
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
}
else if (value == 1)
{
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
}
}
}
*/