xxxxxxxxxx
119
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let ledON = 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);
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;
ledON = 1;
} else {
ledON = 0;
}
}
print(ledON);
}
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 == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
}
}
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 xValue = int(fromArduino[0]);
wind.x = map(xValue, 0, 1023, -1, 1);
}
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
let sendToArduino = ledON + "\n";
writeSerial(sendToArduino);
}
}
//////////////////////////
//////ARDUINO CODE////////
//////////////////////////
// int ledPin = 2;
// void setup() {
// Serial.begin(9600);
// pinMode(LED_BUILTIN, OUTPUT);
// // Outputs on these pins
// pinMode(ledPin, OUTPUT);
// // start the handshake
// while (Serial.available() <= 0) {
// digitalWrite(LED_BUILTIN, HIGH); // on/blink while waiting for serial data
// Serial.println("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
// int right = Serial.parseInt();
// if (Serial.read() == '\n') {
// digitalWrite(ledPin, right);
// int pot = analogRead(A1);
// delay(5);
// Serial.println(pot);
// }
// }
// //digitalWrite(LED_BUILTIN, LOW);
// }