xxxxxxxxxx
82
// This is a modified version of the following sketch.
// https://editor.p5js.org/aaronsherwood/sketches/q2Pl77SWl
//
// LED Brightness is controlled using keyboard keys UP and Down
let b = 0; // LED brightness
function setup() {
createCanvas(600, 360);
textAlign(CENTER,CENTER);
}
function draw() {
background(255);
if (!serialActive) {
console.log("Press Space Bar to select Serial Port");
} else {
console.log("Connected");
}
// displays current brightness
text("Brightness: "+b+"/255",width/2,height/2);
}
function keyPressed() {
// Spacebar to setup the serial connection
// Up and Down keys to control LED brightness
if (key == " ") {
// important to have in order to start the serial connection!!
setUpSerial();
}
if (keyIsDown(UP_ARROW)) {
b = (b>=255) ? 255:b+1;
}
if (keyIsDown(DOWN_ARROW)) {
b = (b<=0) ? 0:b-1;
}
}
function readSerial(data) {
////////////////////////////////////
//READ FROM ARDUINO HERE
////////////////////////////////////
if (data != null) {
// if there is a message from Arduino, continue
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
let sendToArduino = b + "\n";
writeSerial(sendToArduino);
}
}
//Arudino Code
/*
int ledOut = 12;
void setup() {
Serial.begin(9600);
pinMode(12, OUTPUT);
// start the handshake
while (Serial.available() <= 0) {
Serial.println("Wait"); // send a starting message
delay(300); // wait 1/3 second
}
}
void loop() {
// wait for data from p5 before doing something
while (Serial.available()) {
int brightness = Serial.parseInt(); // receives 1 argument, whether the ball hit the ground
if (Serial.read() == '\n') {
analogWrite(ledOut, brightness); // turn on LED if the ball is in contact with the ground (1 -> HIGH) turn off LED if not (0, -> LOW)
Serial.println("OK"); // Send ok sign
}
}
}
*/