Week 11: In Class Exercise

The provided code snippets include p5.js sketches and Arduino code for exercises completed during our class sessions. In these exercises, a potentiometer was utilized as the input sensor.

Exercise #1
Arduino code:

void setup() {
  // Initialize serial communication
  Serial.begin(9600);  
}

void loop() {
  // Read analog value from potentiometer on pin A0
  int sensorValue = analogRead(A0);
  // Print the sensor value to serial monitor
  Serial.println(sensorValue);
  delay(50);
}

P5.js code:

let serial;
let value = 0;

function setup() {
  createCanvas(800, 400);
}

function draw() {
  background(220);
  
  if (!serialActive) {
    text("Press Space Bar to select Serial Port", 20, 30);
  } else {
    text("Connected", 20, 30);
    
    // Display current sensor value
    text('value = ' + str(value), 20, 50);
  }
  
  // Map sensor value to canvas width for circle position
  let xPos = map(value, 0, 1023, 0, width);
  fill(255, 0, 0);
  
  // Draw circle at mapped position
  ellipse(xPos, height/2, 50, 50);  
}

function keyPressed() {
  if (key == " ") {
    // Initialize serial connection when spacebar is pressed
    setUpSerial();  
  }
}

function readSerial(data) {
  if (data != null) {
    // Split incoming data
    let fromArduino = split(trim(data), ",");  
    if (fromArduino.length == 1) {
      // Update value with received data
      value = int(fromArduino[0]);  
    }
    // Prepare mouse Y position to send
    let sendToArduino = mouseY + "\n";  
    // Send data to Arduino
    writeSerial(sendToArduino);  
  }
}

Demo:

Exercise #2
Arduino code:

// Define the pin for LED
const int ledPin = 11;

void setup() {
  Serial.begin(9600);
  
  // Set built-in LED as output
  pinMode(LED_BUILTIN, OUTPUT);  
  
  // Set external LED pin as output
  pinMode(ledPin, OUTPUT); 
  
  // Quick flash of external LED to indicate startup
  digitalWrite(ledPin, HIGH);
  delay(200);
  digitalWrite(ledPin, LOW);
  
  // Handshake loop: blink built-in LED and send "0" until serial data is received
  while (Serial.available() <= 0) {
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println("0");
    delay(300);
    digitalWrite(LED_BUILTIN, LOW);
    delay(50);
  }
}

void loop() {
  while (Serial.available()) {
    // Turn on built-in LED when receiving data
    digitalWrite(LED_BUILTIN, HIGH);  
    
    // Read brightness value from serial
    int brightness = Serial.parseInt();
    if (Serial.read() == '\n') {
      // Set LED brightness
      analogWrite(ledPin, brightness);  
      delay(5);
    }
  }
}

P5.js code:

let serial;
let value = 0;
let brightness = 0;

function setup() {
  createCanvas(800, 400);
}

function draw() {
  background(220);
  
  if (!serialActive) {
    // Display instruction if serial connection is not active
    text("Press Space Bar to select Serial Port", 20, 30);
  } else {
    // Display connection status and current values
    text("Connected", 20, 30);
    text('Brightness = ' + str(brightness), 20, 50);
    text('Value = ' + str(value), 20, 70);
  }

  // Map mouseY position to brightness value
  brightness = map(mouseY, 0, height, 0, 125);
  
  // Visual feedback: draw rectangle with current brightness
  fill(brightness);
  rect(100, 100, 200, 200);
}

function keyPressed() {
  if (key == " ") {
    // Start serial connection when spacebar is pressed
    setUpSerial();
  }
}

function readSerial(data) {
  if (data != null) {
    // Parse incoming data from Arduino
    let fromArduino = split(trim(data), ",");
    if (fromArduino.length == 1) {
      value = int(fromArduino[0]);
    }
    
    // Send brightness value to Arduino
    let sendToArduino = int(brightness) + "\n";
    writeSerial(sendToArduino);
  }
}

Demo:

Exercise #3
Arduino code:

// Define LED pin
const int LED_PIN = 2;    
// Define analog input pin
const int P_PIN = A0;     

void setup() {
  Serial.begin(9600);

  // Set LED pin as output
  pinMode(LED_PIN, OUTPUT);

  // Initially turn off LED
  digitalWrite(LED_PIN, LOW); 

  // Wait for the handshake
  while (Serial.available() <= 0) {
    Serial.println("0");
  }
}

void loop() {
  if (Serial.available()) {
    // Read integer from serial
    int bounce = Serial.parseInt();  
    if (Serial.read() == '\n') { 
       // Set LED state based on input from p5.js
      digitalWrite(LED_PIN, bounce);
    }
  }

   // Read and send analog value
  Serial.println(analogRead(P_PIN));
  
  // Short delay to prevent flooding the serial port
  delay(5);  
}

P5.js code:

let velocity, gravity, position, acceleration, wind;
let sensorData = 0;
const drag = 0.99;
let mass = 50;
let bounce = 0;

function setup() {
  createCanvas(640, 360);
    
  // Initialize vectors for physics simulation
  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 {
    text("Connected", 20, 30);
    text('Sensor = ' + str(sensorData), 20, 50);
    
    // Apply forces when serial is active
    applyForce(wind);
    applyForce(gravity);
  }

  if (serialActive) {
    // Map sensor data to wind force
    wind.x = map(sensorData, 0, 1023, -2, 2);

    // Physics simulation
    applyForce(wind);
    applyForce(gravity);
    velocity.add(acceleration);
    velocity.mult(drag);
    position.add(velocity);
    acceleration.mult(0);

    // Draw the object
    ellipse(position.x, position.y, mass, mass);

    // Handle bouncing
    if (position.y > height-mass/2) {
      velocity.y *= -0.9;
      position.y = height-mass/2;
      bounce = 1;
    } else {
      bounce = 0;
    }
  }
}

// Function to apply force to the object
function applyForce(force) {
  let f = p5.Vector.div(force, mass);
  acceleration.add(f);
}

function keyPressed() {
  if (key == "b") {
    // Reset object with random mass
    mass = random(10,50);
    position.y = -mass;
    velocity.mult(0);
  }
  
  if (key == " ") {
    // Start serial connection
    setUpSerial();
  }
}

// Handle serial communication
function readSerial(data) {
  if (data != null) {
    let fromArduino = split(trim(data), ",");
    if (fromArduino.length == 1) {
      sensorData = int(fromArduino[0]);
    }
    
    // Send bounce state to Arduino
    let sendToArduino = int(bounce) + "\n";
    writeSerial(sendToArduino);
  }
}

Demo:

Leave a Reply