Hi, I’m been working on this project tried to use serial communication to vary the led brightness(vary the duty cycle). Basically the program has 3 function ON, OFF , Brightness. I couldn’t get the brightness function to work. tried so many ways. I’ll inlcude the code for my latest attempt. any help will be greatly appreciated.
int ledPin = 9;
char val;
int brightness = 0;
int fadeamount = 5;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
ONOFF();
bright();
if (Serial.available()) {
val = Serial.read();
}
}
void ONOFF() {
if (val == '1') {
analogWrite(ledPin, HIGH);
} else if ( val =='2') {
digitalWrite(ledPin, LOW);
}
}
void bright() {
if ( val == '3' && brightness == 255) {
analogWrite(ledPin, brightness);
brightness = brightness - 5;
delay(250);
}else if(val == '3' && brightness == 0){
brightness = brightness +5;
delay(250);
}
}
and here is the processing code, serial communication works fine.
import processing.serial.*;
Serial myPort;
void setup() {
size(400, 400);
background(255);
textAlign(CENTER);
rectMode(CENTER);
String portName = Serial.list()[5];
printArray(Serial.list());
myPort = new Serial(this, portName, 9600);
}
void draw() {
fill(0, 255, 0);
rect(200, 100, 200, 80);
fill(0);
textSize(40);
text("ON", 200, 110);
fill(255, 0, 0);
rect(200, 200, 200, 80);
fill(0);
textSize(40);
text("OFF", 200, 210);
fill(120);
rect(200, 300, 200, 80);
fill(0);
textSize(30);
text("BRIGHTNESS", 200, 310);
if (mousePressed&&(mouseY>60)&&(mouseY<140)&&(mouseX>150)&&(mouseX<250)) {
myPort.write('1');
println("1");
fill(255, 255, 0);
rect(200, 100, 200, 80);
}
if (mousePressed&&(mouseY>160)&&(mouseY<240)&&(mouseX>150)&&(mouseX<250)) {
myPort.write('2');
println("2");
fill(255, 255, 0);
rect(200, 200, 200, 80);
}
if (mousePressed&&(mouseY>260)&&(mouseY<340)&&(mouseX>150)&&(mouseX<250)) {
myPort.write('3');
println("3");
fill(255, 255, 0);
rect(200, 300, 200, 80);
}else{
//myPort.write('0');
}
}