Week 11 Serial Communication

Exercise 1

Team members: Nafiha, Javeria

Something that uses only one sensor  on Arduino and makes the ellipse in p5 move on the horizontal axis, in the middle of the screen, and nothing on arduino is controlled by p5.

P5JS code

let redValue = 0;
let transparency = 255;

function setup() {
  createCanvas(640, 480);
  textSize(18);
}

function draw() {
  if (key == " ") {
    initiateSerialConnection();
  }

  background(map(redValue, 0, 1023, 0, 255), 255, 255);
  fill(255, 0, 255, map(transparency, 0, 1023, 0, 255));

  if (!isSerialActive) {
    text("Press Space Bar to select Serial Port", 20, 30);
  } else {
    ellipse(redValue / 2, 240, 100, 100);
  }
}

function keyPressed() {
  if (key == " ") {
    initiateSerialConnection();
  }
}

function readSerial(data) {
  if (data != null) {
    let fromArduino = split(trim(data), ",");
    if (fromArduino.length == 2) {
      redValue = int(fromArduino[0]);
      transparency = int(fromArduino[1]);
    }
  }
}


Arduino code

void setup() {
 Serial.begin(9600);
 pinMode(LED_BUILTIN, OUTPUT);
// start the handshake
 while (Serial.available() <= 0)
{
   Serial.println("0,0"); // send a starting message
   delay(300);            // wait 1/3 second
 }
}
void loop()
{
 // wait for data from p5 before doing something
   while (Serial.available())
{
   digitalWrite(LED_BUILTIN, HIGH); // led on while receiving data
 // Read sensor value
 int sensorValue = analogRead(A0);
  Serial.print(sensorValue);
 // Map sensor value to screen width
 int screenValue = map(sensorValue, 0, 1023, 0, 800);
 // Send mapped value to p5.js
 Serial.println(screenValue);
 delay(50); //    for stability
}
digitalWrite(LED_BUILTIN, LOW);
}

Exercise 2

Something that controls the LED brightness from p5. LED’s brightness is changed by mouseX and the other’s by mouse Y.

P5JS code

let rVal = 0;
let alpha = 255;
let left = 0; // True (1) if mouse is being clicked on left side of screen
let right = 0; // True (1) if mouse is being clicked on right side of screen
function setup() {
 createCanvas(255, 255);
 textSize(18);
}
function draw() {
 // one value from Arduino controls the background's red color
 background(map(rVal, 0, 1023, 0, 255), 255, 255);
 // the other value controls the text's transparency value
 fill(255, 0, 255, map(alpha, 0, 1023, 0, 255));
 if (!serialActive) {
   text("Press Space Bar to select Serial Port", 20, 30);
 } else {
   text("Connected", 20, 30);
  
   // Print the current values
   text('rVal = ' + str(rVal), 20, 50);
   text('alpha = ' + str(alpha), 20, 70);
 }
 // click on one side of the screen, one LED will light up
 // click on the other side, the other LED will light up
 if (mouseIsPressed) {
   if (mouseX <= width / 2) {
     left = 1;
   } else {
     right = 1;
   }
 } else {
   left = right = 0;
 }
}
function keyPressed() {
 if (key == " ") {
   // important to have in order to start the serial connection!!
   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 == 2) {
     // 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
     rVal = int(fromArduino[0]);
     alpha = int(fromArduino[1]);
   }
   //////////////////////////////////
   //SEND TO ARDUINO HERE (handshake)
   //////////////////////////////////
  
   let sendToArduino = mouseX + "," + mouseY + "\n";
   writeSerial(sendToArduino);
 }
}

Arduino code

int leftLedPin = 2;
int rightLedPin = 5;
void setup() {
 // Start serial communication so we can send data
 // over the USB connection to our p5js sketch
 Serial.begin(9600);
 // We'll use the builtin LED as a status output.
 // We can't use the serial monitor since the serial connection is
 // used to communicate to p5js and only one application on the computer
 // can use a serial port at once.
 pinMode(LED_BUILTIN, OUTPUT);
 // Outputs on these pins
 pinMode(leftLedPin, OUTPUT);
 pinMode(rightLedPin, OUTPUT);
 // Blink them so we can check the wiring
 digitalWrite(leftLedPin, HIGH);
 digitalWrite(rightLedPin, HIGH);
 delay(200);
 digitalWrite(leftLedPin, LOW);
 digitalWrite(rightLedPin, LOW);
 // start the handshake
 while (Serial.available() <= 0) {
   digitalWrite(LED_BUILTIN, HIGH); // on/blink while waiting for serial data
   Serial.println("0,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 posX = Serial.parseInt();
   int posY = Serial.parseInt();
   if (Serial.read() == '\n') {
     analogWrite(leftLedPin, posX);
     analogWrite(rightLedPin, posY);
     int sensor = analogRead(A0);
     delay(5);
     int sensor2 = analogRead(A1);
     delay(5);
     Serial.print(sensor);
     Serial.print(',');
     Serial.println(sensor2);
   }
 }
 digitalWrite(LED_BUILTIN, LOW);
}

Exercise 3

Bouncing ball: potentiometer is used as the analog sensor to control the breeze.

P5JS code

let velocity;
let gravity;
let position;
let acceleration;
let breeze;
let drag = 0.99;
let mass = 50;
let heightOfBall = 0;
function setup() {
  createCanvas(640, 360); // Create a canvas of 800x400 pixels
 
  noFill();
  position = createVector(width/2, 0);
  velocity = createVector(0,0);
  acceleration = createVector(0,0);
  gravity = createVector(0, 0.5*mass);
  breeze = createVector(0,0); 
}
function draw() {
  background(215);
  fill(0);
  
  if (!serialActive) {
    text("Press the space bar to select the serial Port", 20, 30);
  }
  else 
  {
    text("Arduino is connected! Press b to jump.", 20, 30);
  
  applyForce(breeze);
  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;
    
    heightOfBall = 0;
    
    } 
    else {
      heightOfBall = 1;
    }
  }
}
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();
  }   
  else if (key=='b'){
    mass=random(15,80);
    position.y=-mass;
    velocity.mult(0);
  }
}
// this callback function
function readSerial(data) {
    ////////////////////////////////////
    //READ FROM ARDUINO HERE
    ////////////////////////////////////
  
     if (data != null) {
    // make sure there is actually a message
    
    let fromArduino = split(trim(data), ",");
    
       // if the right length, then proceed
    if (fromArduino.length == 1) {
//sensor value is the input from potentiometer
      let sensorVal = int(fromArduino[0]);
      
//potentiometer value ranges from 0 - 1023
//for values less than 400,wind blows to right
      if (sensorVal < 400){
        breeze.x=1
      }
//if value between 400 and 500, wind stops so ball stops
      else if(sensorVal >= 400 && sensorVal < 500){
        breeze.x = 0
      }
//if value greater than 500, wind blows to left
      else {
        breeze.x = -1
      }
          //////////////////////////////////
          //SEND TO ARDUINO HERE (handshake)
          //////////////////////////////////
    }
//height of ball sent to arduino to check if ball on floor or not
    let sendToArduino = heightOfBall  + "\n";
    writeSerial(sendToArduino);
  }
}

Arduino code

const int poten_pin = A0;
const int ledPin = 2;
void setup() {
 Serial.begin(9600); // Start serial communication at 9600 bps
 pinMode(LED_BUILTIN, OUTPUT);
 pinMode(ledPin, OUTPUT);
 pinMode(poten_pin, INPUT);
 // start the handshake
 while (Serial.available() <= 0) {
   digitalWrite(LED_BUILTIN, HIGH); // on/blink while waiting for serial data
   Serial.println("0,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);
     digitalWrite(ledPin, LOW);
//read the position of ball from p5
     int position = Serial.parseInt();
  
     if (Serial.read() == '\n') {
       // Read potentiometer value
     int sensorValue = analogRead(poten_pin);
     //send value to p5
     Serial.println(sensorValue);
     }
//if ball is touching the ground i.e. height is zero, turn LED on
     if (position == 0)
     {
       digitalWrite(ledPin, HIGH);
     }
     else{
       digitalWrite(ledPin, LOW);
     }
   }
     digitalWrite(LED_BUILTIN, LOW);
   }

 

 

Leave a Reply