For this week’s assignment, Aysha and I worked on three different exercises that focused on serial communication.
Exercise 1: Moving p5.js ball with potentiometer
p5.js code:
//Variable to declare the ellipse moving acorss the x-axis
let ellipseX;
function setup() {
//Canvas dimensions
createCanvas(400, 400);
//Set text size to 18 pixels
textSize(18);
//Initializes ellipse to half the width of the canvas, essentially centers it
ellipseX = width/2;
}
function draw() {
//Sets background to a light purple shade
background("rgb(185,185,228)");
// SetS fill color for the ellipse
fill("rgb(142,142,228)");
// Sets stroke color/outline for the ellipse
stroke("rgb(91,91,233)");
// Draw ellipse at ellipseX position, centered vertically, with a diameter of 120 pixels
ellipse(ellipseX, height / 2, 120, 120);
// If serial connection is not active, display message to prompt user to select serial port
if (!serialActive) {
//Sets fill color to white
fill('white');
// Sets stroke color to a gray shade
stroke('#666666')
// Display instructions at (15, 30)
text("Press Space Bar to select Serial Port", 15, 30);
}
// If serial connection is active, display "Connected" message
else {
// Display instructions at (15, 30)
text("Connected", 15, 30);
}
}
// Function to handle key presses
function keyPressed() {
// If space bar is pressed, call setUpSerial() function
if (key == " ") {
setUpSerial();
}
}
// Function to read data from the serial port
function readSerial(data) {
// Check if data is not null
if (data != null) {
// Split the received data into an array using comma as delimiter
let fromArduino = split(trim(data), ",");
// Map the potentiometer value to adjust the position of the ellipse
ellipseX = map(int(fromArduino[0]), 0, 1023, 0, width);
}
}
Arduino Code:
const int potPin = A1; // Analog pin connected to the potentiometer
void setup() {
Serial.begin(9600);
}
void loop() {
int potValue = analogRead(potPin); // Read the value from the potentiometer
// Send the potentiometer value to p5.js
Serial.println(potValue);
}
Exercise 2: Controlling LED with p5.js slider
p5.js code:
// Variable to hold the brightness value
let brightness = 0;
// Variable to hold the slider
let slider;
function setup() {
//Canvas dimensions
createCanvas(400, 400);
// Create slider with range from 0 to 255 and initial value of 100
slider = createSlider(0, 255, 100);
// Positions slider horizontally centered and vertically centered
slider.position(132, height/2);
}
function draw() {
// Sets background color to a light gray shade
background('#ADB9C7');
// Gets current value of the slider
let val = slider.value();
// Updates brightness variable with the slider value
brightness = val;
//If brightness is maximum (255), change background color to light blue
if (brightness == 255) {
// Changes background color to gold when brightness is max
background('#DCECFF');
}
// If serial connection is not active, display message to prompt user to select serial port
if (!serialActive) {
// Set fill color to blue
fill('#0876FF');
// Set stroke color to a light gray shade
stroke('#B2B2B2');
// Set text size to 16 pixels
textSize(16);
// Display instructions at (20, 30)
text("Press Space Bar to select Serial Port", 20, 30);
}
// If serial connection is active, display "Connected" message
else {
textSize(16);
// Display instructions at (29, 30)
text("Connected",29,30);
}
}
// Function to handle key presses
function keyPressed() {
// If space bar is pressed, start the serial connection
if (key == " ") {
setUpSerial();
}
}
// Function to send data to the serial port
function readSerial(data) {
// Check if data is not null
if (data != null) {
//Creates a string to send to Arduino with brightness value followed by newline character (HANDSHAKE)
let sendToArduino = brightness + "\n";
// Send data to Arduino
writeSerial(sendToArduino);
}
}
Arduino code:
int LED = 5; //PWM PIN
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(9600);
// initializing handshake
while (Serial.available() <= 0) {
Serial.println("Initializing Connection");
delay(200); // wait 1/2 second
}
}
void loop() {
// wait for data to load from p5 before continuing code
while (Serial.available()) {
int brightness = Serial.parseInt();
if (Serial.read() == '\n') {
analogWrite(LED, brightness); // turn on LED and adjusts brightness
Serial.println("ON");
}
}
}
Exercise 3: Blink LED with bouncing ball and move wind with potentiometer
p5.js code:
let velocity;
let gravity;
let position;
let acceleration;
let wind;
let drag = 0.99;
let mass = 70;
// ball bounce check to control LED
let ballBouncing = 0;
function setup() {
createCanvas(400, 400);
textSize(width/25);
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(210, 230, 250);
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
applyForce(wind);
applyForce(gravity);
velocity.add(acceleration);
velocity.mult(drag);
position.add(velocity);
acceleration.mult(0);
// Check boundaries for right and left movement
if (position.x > width - mass / 2) {
position.x = width - mass / 2;
velocity.x *= -0.9; // Reverse velocity when hitting right boundary
} else if (position.x < mass / 2) {
position.x = mass / 2;
velocity.x *= -0.9; // Reverse velocity when hitting boundary
}
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;
ballBouncing = 1;
} else {
ballBouncing = 0;
}
}
}
function keyPressed() {
if (key == " ") {
// to start serial connection
setUpSerial();
} else if (key == "ENTER") {
mass = random(15, 80);
position.y = -mass;
velocity.mult(0);
}
}
function readSerial(data) {
if (data != null) {
// make sure there is a message and split it
let fromArduino = split(trim(data), ",");
// if it's the right length, then proceed
if (fromArduino.length == 1) {
// only store values here
let potentiometerValue = int(fromArduino[0]);
wind.x = map(potentiometerValue, 0, 1023, -1, 1);
}
// ARDUINO HANDSHAKE
let sendToArduino = ballBouncing + "\n";
writeSerial(sendToArduino);
}
}
function applyForce(force) {
// Newton's 2nd law: F = M * A
// or A = F / M
let f = p5.Vector.div(force, mass);
acceleration.add(f);
}
Arduino code:
//int ledPin = 5;
//const int potPin=A1;
//void setup() {
// Start serial communication so we can send data
// over the USB connection to our p5js sketch
//Serial.begin(9600);
//pinMode(LED_BUILTIN, OUTPUT);
//pinMode(ledPin, OUTPUT);
//pinMode(potPin, 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); // led on while receiving data
//digitalWrite(ledPin, LOW);
//int ballBouncing =Serial.parseInt();
//if (Serial.read() == '\n') {
//int potPinValue = analogRead(potPin); delay(5);
//Serial.println(potPinValue);
//}
// Set LED brightness based on whether the ball is bouncing
//if (ballBouncing == 1) {
//digitalWrite(ledPin, HIGH);
//} else {
//digitalWrite(ledPin, LOW);
//}
//}
//digitalWrite(LED_BUILTIN, LOW);
//}














