xxxxxxxxxx
61
/*
Control the brightness of an LED through p5.
Arduino code:
https://github.com/vsharkovski/nyuad-coursework/blob/main/introim/arduino/led-p5/led-p5.ino
*/
let lastDistance = 0;
function setup() {
createCanvas(640, 480);
textSize(18);
}
function draw() {
background(0);
fill(255);
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
ellipseMode(CENTER);
stroke(255);
noFill();
ellipse(width / 2, height / 2, 50, 50);
if (mouseIsPressed) {
lastDistance = dist(width / 2, height / 2, mouseX, mouseY);
line(width / 2, height / 2, mouseX, mouseY);
}
}
}
function keyPressed() {
if (key == " ") {
setUpSerial();
}
}
function readSerial(data) {
if (data != null) {
// Make sure there is actually a message. Split the message.
let fromArduino = split(trim(data), ",");
if (fromArduino.length == 1) {}
// Send to Arduino.
let bright = map(lastDistance, 0, sqrt(height*height + width*width), 0, 255);
bright = round(bright);
if (frameCount % 60 == 0) {
print("brightness", bright);
}
let sendToArduino = `${bright}\n`;
writeSerial(sendToArduino);
}
}