Combining p5 and Arduino

Hey Fellas!

This week we did something really exciting in class! We combined ICM and Pcomp in one single project (BOOM!)

The goal was to create a “1 button” circuit that would trigger the code written in p5.js.

So me and my classmate Yuli drew a sketch in p5.js in which 2 objects get closer to each other and meet in the middle of the canvas. They’re movement is controlled according to the pressure the user puts in a force sensitive resistorĀ , which is connected to the Arduino.

Here is our result:

After that I decided to make some changes on my own to the sketch. So I switched the characters to a princess and a frog <3 (used illustrator to draw both).

CheckĀ it out:

 

This is the p5.js code we used:
var serial;
var speed = 0;

var manleftx = -100;
var manrightx = 700;

function preload() {
manleft = loadImage(‘princess.png’);
manright = loadImage(‘frog-2.png’);
}

function setup() {
createCanvas(1000, 350);

// Instantiate our SerialPort object
serial = new p5.SerialPort();

// Assuming our Arduino is connected, let’s open the connection to it
// Change this to the name of your arduino’s serial port
serial.open(“/dev/cu.usbmodem1411”);

// if you need to see the list
// serial.onList(gotList);

// This is a new concept!
// Whenever there is new data, the “gotData” function happens.
// This is called a *CALLBACK*
serial.onData(gotData);
}

// This happens when there is data
function gotData() {
// Read the data as text (a string)!
var data = serial.readLine();

if (data.length > 0); {

if(data == “0”){
speed = -5;
if (manleftx < -100) {
speed = 0;
}
}else{
speed = Number(data) / 100;
if (manleftx >= width/2-235) {
speed = 0;
}
}

}

//print (speed);
}

function draw() {
background(255, 51, random (180, 230));

textSize (50);
text(“hmmmm, that’s gross”,width/2-250,height/2);

image(manleft, manleftx, 0, 400, 400);
image(manright, manrightx, 0, 400, 400);

manleftx = manleftx + speed;
manrightx = manrightx – speed;
}
/*
// Got the list of ports
function gotList(thelist) {
println(“List of Serial Ports:”);
// theList is an array of their names
for (var i = 0; i < thelist.length; i++) {
// Display in the console
println(i + ” ” + thelist[i]);
}
}*/

 

And this is the Arduino code:

// Analog Sensor

int inPin = A0; // Sensor connected to analog pin 0
int val = 0; // variable to store the read value

int Pin2 = A1;
int val2 = 0;

void setup() {
Serial.begin(9600);
pinMode(inPin, INPUT);
pinMode(Pin2, INPUT);
}

void loop() {
Serial.println(val2);

val = analogRead(inPin); // read the input pin
delay(33); // 30 frames per second

val2 = analogRead(Pin2);
delay(33);
}

Leave a Reply

Your email address will not be published. Required fields are marked *