WEEK 11

PROMPT 1

Code

//declaring variables
let serial;
let photoValue = 0;
let xPos = 0;
let Size = 80;
let yPos = 200;

function setup() {
  createCanvas(400, 400);
  serial = new p5.SerialPort();
  serial.open('/dev/tty.usbmodem1301');
  serial.on('data', readSerialData); // call readSerialData when new data is received
}

function draw() {
  background(220);
  fill("red");
  ellipse(xPos, yPos, Size, Size);
}

function readSerialData() {
  let data = serial.readLine(); // read the incoming data
  if (data) {
    photoValue = Number(data); // convert the data to a number
    xPos = map(photoValue, 0, 1023, 0, width); // map the photo sensor value to the x-position of the ellipse
  }
}

Video

 

PROMPT 2

CODE

let serial;
let brightness = 0; // variable to store LED brightness

function setup() {
  serial = new p5.SerialPort();
  serial.open('/dev/tty.usbmodem1301');
  createCanvas(400, 400);
}

function draw() {
  background(220);
  text("LED Brightness: " + brightness, 50, 50);

  // send data to Arduino over serial
  if (frameCount % 10 == 0) {
    serial.write(brightness);
  }
}

function keyPressed() {
  if (keyCode === UP_ARROW && brightness < 255) {
    brightness += 10; // increase brightness by 10
  } else if (keyCode === DOWN_ARROW && brightness > 0) {
    brightness -= 10; // decrease brightness by 10
  }
}

VIDEO

 

PROMPT 3

CODE

let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 50;
let lightVal = 0;
let ledState = false;

let serial;
let led;

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);

  serial = new p5.SerialPort();
  serial.open('/dev/tty.usbmodem1301');
  serial.on("data", serialEvent);

  led = new p5.SerialPort();
  led.open('/dev/tty.usbmodem1301');
}

function draw() {
  background(255);

  wind.x = map(lightVal, 0, 1023, -1, 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) {
    velocity.y *= -0.9;  // A little dampening when hitting the bottom
    position.y = height-mass/2;
    led.write("L"); // Turn off the LED when the ball hits the ground
  } else {
    led.write("H"); // Turn on the LED when the ball is in the air
  }
}

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 serialEvent() {
  lightVal = Number(serial.readLine());
}

function keyPressed(){
  if (keyCode==LEFT_ARROW){
    wind.x=-1;
  }
  if (keyCode==RIGHT_ARROW){
    wind.x=1;
  }
  if (key==' '){
    mass=random(15,80);
    position.y=-mass;
    velocity.mult(0);
  }
}

VIDEO

 

Leave a Reply