xxxxxxxxxx
119
// name: Adina Maratkyzy
// date: 13 April 2023
// class: Intro to IM
// professor: Michael Shiloh
// description:
// week 11 homework ex.2 -
// changing LED brightness by clicking on screen
let left = 0;
let right = 0;
let brightness = 0;
function setup() {
createCanvas(640, 480);
textSize(18);
}
function draw() {
background(255, 230, 240);
stroke(200, 20, 200);
line(width / 2, 0, width / 2, height);
noStroke();
if (!serialActive) {
text("Press Space Bar to select Serial Port", 20, 30);
} else {
text("Connected", 20, 30);
text("dimmer", width / 5, height / 2);
text("brighter", width / 1.45, height / 2);
//check if count is correct
print(
"left:" +
(left - 1) +
", " +
"right:" +
right +
", " +
"brightness:" +
brightness
);
}
}
function mousePressed() {
// click on left side of the screen -> LED gets dimmer
// click on right side of the screen -> LED gets brighter
if (mouseX <= width / 2) {
left++;
brightness = brightness - 10;
} else {
right++;
brightness = brightness + 10;
}
// check if brightness reaches limits
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();
}
}
function readSerial(data) {
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 == 1) {
// 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 ledPin = 5;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(ledPin, 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(ledPin, brightness);
}
digitalWrite(LED_BUILTIN, LOW);
}
*/