xxxxxxxxxx
99
/* Week 11.2 bidi serial example
* Originally by Aaron Sherwood
* Modified by Mangtronix
*
* Add this library to Sketch files
* https://github.com/mangtronix/IntroductionToInteractiveMedia/blob/master/code/p5.web-serial.js files
*
* You must include this line in your index.html (in Sketch Files) to load the
* web-serial library
*
* <script src="p5.web-serial.js"></script>
*
* Arduino code:
* https://github.com/mangtronix/IntroductionToInteractiveMedia/blob/master/code/Week11Serial.ino
*/
let rVal = 0;
let alpha = 255;
let brightness = 0;
function setup() {
createCanvas(640, 480);
textSize(18);
}
function draw() {
fill(242,97,97);
rect(0,0,213,480);
fill(240,57,57);
rect(214,0,426,480);
fill(154,7,7);
rect(427,0,640, 480);
// the other value controls the text's transparency value
fill(0);
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
// Print the current values
text("rVal = " + str(rVal), 20, 50);
text("alpha = " + str(alpha), 20, 70);
}
// click on one side of the screen, one LED will light up
if (mouseIsPressed) {
if (mouseX >= 0 && mouseX <= 213) {
brightness = 30;
} else if (mouseX >= 214 && mouseX <= 426) {
brightness = 100;
} else {
brightness = 200;
}
}
}
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
// We take the string we get from Arduino and explicitly
// convert it to a number by using int()
// e.g. "103" becomes 103
rVal = int(fromArduino[0]);
alpha = int(fromArduino[1]);
}
//SEND TO ARDUINO HERE (handshake)
let sendToArduino = brightness + "\n";
writeSerial(sendToArduino);
}
}