xxxxxxxxxx
133
// name: Adina Maratkyzy
// date: 13 April 2023
// class: Intro to IM
// professor: Michael Shiloh
// description:
// week 11 homework ex.3 -
// gravity wind example with LED lighting up everytime ball touches the ground and potentiometer being used to control the direction and power of the wind
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let isBouncing = 0;
function setup() {
createCanvas(640, 480);
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, 230, 240);
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
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;
isBouncing = 1;
} else {
isBouncing = 0;
}
}
}
function keyPressed() {
if (key == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
} else if (key == "ENTER") {
mass = random(15, 80);
position.y = -mass;
velocity.mult(0);
}
}
function readSerial(data) {
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
let potValue = int(fromArduino[0]);
wind.x = map(potValue, 0, 1023, -1, 1);
}
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
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);
}
//Arduino Code
/*
int ledPin = 2;
const int potPin = A1;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(potPin, INPUT);
// start the handshake
while (Serial.available() <= 0) {
digitalWrite(LED_BUILTIN, HIGH); // on/blink while waiting for serial data
Serial.println("0,0"); // send a starting message
delay(300); // wait 1/3 second
digitalWrite(LED_BUILTIN, LOW);
delay(50);
}
}
void loop() {
// wait for data from p5 before doing something
while (Serial.available()) {
digitalWrite(LED_BUILTIN, HIGH); // led on while receiving data
digitalWrite(ledPin, LOW);
int isBouncing = Serial.parseInt();
if (Serial.read() == '\n') {
int potValue = analogRead(potPin);
delay(5);
Serial.println(potValue);
}
// Set LED brightness based on whether bouncing.
if (isBouncing == 1) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
digitalWrite(LED_BUILTIN, LOW);
}
*/