xxxxxxxxxx
67
let brightness = 0; // Brightness value to send to Arduino
function setup() {
createCanvas(640, 480);
textSize(18);
// Check if serial is active and set it up if not
if (!serialActive) {
setUpSerial(); // Initialize serial communication
}
}
function draw() {
background(30); // Dark background
fill(255); // White text
text("Use the UP and DOWN arrows to control LED brightness", 20, 30);
// Display the current brightness value
text("Brightness: " + brightness, 20, 60);
}
function keyPressed() {
if (keyCode === UP_ARROW) {
// Increase brightness
brightness = min(brightness + 10, 255); // Max brightness is 255
sendBrightness();
} else if (keyCode === DOWN_ARROW) {
// Decrease brightness
brightness = max(brightness - 10, 0); // Min brightness is 0
sendBrightness();
} else if (key === " ") {
// Start serial connection when spacebar is pressed
setUpSerial();
}
}
function sendBrightness() {
if (writer) {
// Send the brightness value to Arduino
writer.write(brightness + "\n");
} else {
console.error("Writer is not available. Please connect to the serial port.");
}
}
// ARDUINO CODE
// int ledPin = 9; // LED connected to PWM pin 9
// int brightness = 0; // Variable to store brightness value from p5.js
// void setup() {
// Serial.begin(9600); // Start serial communication
// pinMode(ledPin, OUTPUT); // Set LED pin as an output
// }
// void loop() {
// // Check if data is available to read
// if (Serial.available() > 0) {
// // Read the brightness value sent from p5.js
// brightness = Serial.parseInt();
// // Constrain the brightness value to 0-255
// brightness = constrain(brightness, 0, 255);
// // Set the LED brightness
// analogWrite(ledPin, brightness);
// }
// }