Arduino & p5.js
[Nikita and Genesis]
Each exercise focuses on the communication between the Arduino’s physical components and visual output through serial communication.
Exercise 1: Moving an Ellipse with One Sensor
video
Arduino Code:
void setup(){ Serial.begin(9600); } void loop(){ int pot = analogRead(A0); // send mapped X (0–400) to p5 int xPos = map(pot, 0, 1023, 0, 400); Serial.println(xPos); delay(30); }
circuit:
Explanation:
This exercise uses a single analog sensor (potentiometer) connected to Arduino to control the horizontal position of an ellipse in p5.js. The Arduino reads the potentiometer value and sends it over Serial to the p5.js sketch, which updates the x-position of the ellipse accordingly. The communication is one-way: Arduino → p5.js.
Exercise 2: Controlling LED Brightness from p5.js
video
Arduino Code:
// Arduino: LED brightness via Serial.parseInt() const int ledPin = 9; // PWM-capable pin void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); } void loop() { if (Serial.available() > 0) { int brightness = Serial.parseInt(); // Read integer from serial brightness = constrain(brightness, 0, 255); // Clamp analogWrite(ledPin, brightness); } }
circuit:
Explanation:
In this exercise, the communication is reversed. The p5.js sketch sends a brightness value (0–255) to Arduino via Serial, which adjusts the brightness of an LED connected to a PWM-capable pin (pin 9). This demonstrates real-time control from software (p5.js) to hardware (Arduino).
Exercise 3: Gravity Wind with LED Bounce Indicator
video
Arduino Code:
/* * Exercise 3 Arduino: * - Read pot on A0, send sensorValue to p5.js * - Listen for 'B' from p5.js → blink LED on pin 9 */ const int sensorPin = A0; const int ledPin = 9; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); } void loop() { // Read and send sensor int sensorValue = analogRead(sensorPin); Serial.println(sensorValue); // Check for bounce command if (Serial.available() > 0) { char inChar = Serial.read(); if (inChar == 'B') { digitalWrite(ledPin, HIGH); delay(100); digitalWrite(ledPin, LOW); } } delay(20); }
circuit:
Explanation:
This sketch is a modified version of the classic p5.js Gravity + Wind example. An analog sensor (potentiometer) on Arduino controls the wind force in p5.js. Every time the ball hits the bottom (a “bounce”), p5.js sends a command (‘B’) back to Arduino via Serial, which briefly lights up an LED. This showcases a complete two-way communication system between Arduino and p5.js.