xxxxxxxxxx
112
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let sensorValue = 0; // Variable to store wind value from Arduino
let windStrength = 0; // Wind force determined by the sensor
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);
// Initialize serial communication
if (!serialActive) {
setUpSerial();
}
}
function draw() {
background(255);
// Apply gravity
applyForce(gravity);
// Apply wind (continuously updated from sensor)
wind.x = map(sensorValue, 0, 1023, -2, 2); // Map sensor value to a stronger wind range
applyForce(wind);
// Update position and velocity
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
// Draw the ball
ellipse(position.x, position.y, mass, mass);
// Check for bounce
if (position.y > height - mass / 2) {
velocity.y *= -0.9; // A little dampening when hitting the bottom
position.y = height - mass / 2;
// Notify Arduino about the bounce
sendBounce();
}
}
function applyForce(force) {
// Newton's 2nd law: F = M * A
let f = p5.Vector.div(force, mass);
acceleration.add(f);
}
// Notify Arduino when the ball bounces
function sendBounce() {
if (writer) {
writer.write('1\n'); // Send the bounce signal
}
}
// Read wind control value from Arduino
function readSerial(data) {
if (data != null) {
// Parse the sensor value directly into a variable for wind force
sensorValue = int(trim(data));
}
}
// Handle serial setup (using the serial.js file)
function keyPressed() {
if (key === " ") {
setUpSerial();
}
}
// ARDUINO CODE
// const int ledPin = 9; // LED connected to pin 9
// const int sensorPin = A0; // Analog sensor for wind control
// int sensorValue = 0; // Variable to store sensor value from analog pin
// void setup() {
// Serial.begin(9600); // Start serial communication
// pinMode(ledPin, OUTPUT); // Set LED pin as output
// }
// void loop() {
// // Read the sensor value and send it to p5.js
// sensorValue = analogRead(sensorPin);
// Serial.println(sensorValue);
// // Check if a bounce signal is received
// if (Serial.available() > 0) {
// char command = Serial.read();
// if (command == '1') {
// // Turn on the LED
// digitalWrite(ledPin, HIGH);
// delay(100); // Keep the LED on briefly
// digitalWrite(ledPin, LOW); // Turn off the LED
// }
// }
// }