ARDUINO ↔ P5.JS
Week 07 - 10/19/2022
Serial Output to p5.js | p5.serialcontrol
Being able to connect Arduino to p5.js is fun and versatile. This opens up almost unlimited ways and possibilities to approach different projects and make something playful in both open-source ends.
In this lab, p5.serialcontrol is used to connect Arduino with p5.js. A rectangle is drawn on the p5 canvas, and the goal is to rotate the rectangle by using a potentiometer on the breadboard. Firstly, Arduino Nano 33 IoT needs to read the analog input from the potentiometer. Then, p5.serialcontrol translates the data to p5 sketch and then the number (0 - 1023) is mapped to degrees (0 - 360), in order to make the rectangle rotate. Below are the code examples for both Arduino IDE and p5.js.
// reference:
// https://gist.github.com/shfitz/b78b412960fba668d08ccc84b9ee838d
// pin the pot is connected to
const int potPin = A0;
// variable to hold the value from the potentiometer
int potVal = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
// read the value of the pot and store it
potVal = analogRead(potPin);
// write the value out to the serial port
Serial.println(potVal);
// wait a bit for between readings
delay(10);
}
Arduino:
let serial; // variable for the serial object
let latestData = "waiting for data"; // variable to hold the data
function setup() {
createCanvas(windowWidth, windowHeight);
// serial constructor
serial = new p5.SerialPort();
// serial port to use - *user will need to update port number*
serial.open('/dev/tty.usbmodem101');
// what to do when we get serial data
serial.on('data', gotData);
}
// when data is received in the serial buffer
function gotData() {
let currentString = serial.readLine(); // store the data in a variable
trim(currentString); // get rid of whitespace
if (!currentString) return; // if there's nothing in there, ignore it
console.log(currentString); // print it out
latestData = currentString; // save it to the global variable
}
function draw() {
background(255, 255, 255);
fill(0, 0, 0);
text(latestData, 10, 10); // print the data to the sketch
// in this example, we are reciving a value between 0 and 1023
// and using that to rotate the square
angleMode(DEGREES);
let rotDeg = map(latestData, 0, 1023, 0 ,360);
translate(width / 2, height / 2);
rotate(rotDeg);
rectMode(CENTER);
rect(0, 0, 100, 100);
}
p5.js: