xxxxxxxxxx
125
let brightness = 0;
let left = 0;
let right = 0;
function setup() {
createCanvas(600, 400);
textSize(20);
}
function draw() {
background(230, 230, 250);
line(width / 2, 35, width / 2, height); // a line in the middle so it is easier to distinguish between left and right
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
// Print the current values
text("brightness:" + brightness);
}
}
function mousePressed() {
// click on left side of the screen
// LED will get dimmer
// click on right side of the screen
// LED will brighten up
if (mouseX <= width / 2) {
left++;
brightness = brightness - 5;
} else {
right++;
brightness = brightness + 5;
}
// to check the limits of the brightness
// and make it not go over 0 or 255
if (brightness <= 0) {
brightness = 0;
} else if (brightness >= 255) {
brightness = 255;
}
}
function keyPressed() {
if (key == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
}
}
// This function will be called by the web-serial library
// with each new *line* of data. The serial library reads
// the data until the newline and then gives it to us through
// this callback function
function readSerial(data) {
////////////////////////////////////
//READ FROM ARDUINO HERE
////////////////////////////////////
if (data != null) {
// make sure there is actually a message
// split the message
let fromArduino = split(trim(data), ",");
// if the right length, then proceed
if (fromArduino.length == 2) {
// only store values here
// do everything with those values in the main draw loop
}
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
let sendToArduino = brightness + "\n";
writeSerial(sendToArduino);
}
}
//Arduino Code
/*
int leftLedPin = 5;
void setup() {
// Start serial communication so we can send data
// over the USB connection to our p5js sketch
Serial.begin(9600);
// We'll use the builtin LED as a status output.
// We can't use the serial monitor since the serial connection is
// used to communicate to p5js and only one application on the computer
// can use a serial port at once.
pinMode(LED_BUILTIN, OUTPUT);
// Outputs on these pins
pinMode(leftLedPin, OUTPUT);
// start the handshake
while (Serial.available() <= 0) {
digitalWrite(LED_BUILTIN, HIGH); // on/blink while waiting for serial data
Serial.println("0,0"); // send a starting message
delay(300); // wait 1/3 second
digitalWrite(LED_BUILTIN, LOW);
delay(50);
}
}
void loop() {
// wait for data from p5 before doing something
while (Serial.available()) {
digitalWrite(LED_BUILTIN, HIGH); // led on while receiving data
int brightness = Serial.parseInt();
if (Serial.read() == '\n') {
delay(5);
Serial.println("1");
}
analogWrite (leftLedPin, brightness);
}
digitalWrite(LED_BUILTIN, LOW);
}
*/