Homework – In class Assignments

Example 1:

// Map the sensor value to the width of the canvas
  ellipseX = map(latestData, 0, 1023, 0, width);

  // Draw the ellipse at the mapped position
  ellipse(ellipseX, height/2, 50, 50);

Example 2:

I simply map the mouseX coordinate to the light’s brightness!

if (mouseIsPressed) {
light=map(mouseX,0,width,0,1023);
}

 

Example 3:

let velocity;
let gravity;
let position;
let old_position;
let acceleration;
let wind;
let wind_arduino=0;
let drag = 0.99;
let mass = 50;
let light =0;

function setup() {
  createCanvas(640, 360);
  noFill();
  position = createVector(width/2, 0);
  velocity = createVector(0,0);
  acceleration = createVector(0,0);
  gravity = createVector(0, 0.1*mass);
  wind = createVector(0,0);
  noLoop();
}

function draw() {
  background(255);
  
  if(wind_arduino<512)
    wind.x=-1;
  else
    wind.x=1;
  applyForce(wind);
  applyForce(gravity);
  velocity.add(acceleration);
  velocity.mult(drag);
  old_position=position.y;
  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;
    }
   print(height-mass/2);
  if (position.y >= 334)
  {
    light=1;
  }
  else
    light=0;
  if(old_position==position.y)
    light=0;
}

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==' '){
    loop();
    setUpSerial();
  }
}

// This function will be called by the web-serial library
// with each new *line* of data. The serial library reads
// the data until the newline and then gives it to us through
// this callback function
function readSerial(data) {
  ////////////////////////////////////
  //READ FROM ARDUINO HERE
  ////////////////////////////////////

  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
      
      // We take the string we get from Arduino and explicitly
      // convert it to a number by using int()
      // e.g. "103" becomes 103
      print(fromArduino[0]);
      wind_arduino = int(fromArduino[0]);
    }

    //////////////////////////////////
    //SEND TO ARDUINO HERE (handshake)
    //////////////////////////////////
    let sendToArduino = light+"\n";
    writeSerial(sendToArduino);
  }
}

Leave a Reply