I'm a new arduino user, so I'm learning now...
I want make a new class to control my RGB led...
I already use this led with a method on my code... But I want to generalize the code to put more led without ctrl+c ctrl+v my code.
I create the class:
/*
STATUSLED CLASS DEFINITION
*/
class StatusLED {
int pinVermelho;
int pinVerde;
int pinAzul;
public:
StatusLED(int pinRed, int pinGreen, int pinBlue) {
this->pinVermelho = pinRed;
this->pinVerde = pinGreen;
this->pinAzul = pinBlue;
}
void RGB(int red, int green, int blue) {
Serial.print("StatusLED.RGB(");
Serial.print(red);
Serial.print(", ");
Serial.print(green);
Serial.print(", ");
Serial.print(blue);
Serial.println(");");
digitalWrite(pinVermelho, 255 - red);
digitalWrite(pinVerde, 255 - green);
digitalWrite(pinAzul, 255 - blue);
}
};
I initialize that with the pins of my RBG led:
#define pinoAzul 9
#define pinoVerde 10
#define pinoVermelho 11
StatusLED led(pinoVermelho, pinoVerde, pinoAzul);
And to test it I use:
void setup() {
pinMode(pinoAzul, OUTPUT);
digitalWrite(pinoAzul, LOW);
pinMode(pinoVerde, OUTPUT);
digitalWrite(pinoVerde, LOW);
pinMode(pinoVermelho, OUTPUT);
digitalWrite(pinoVermelho, LOW);
}
void loop() {
led.RGB(255, 0, 0);
delay(1000);
led.RGB(0, 255, 0);
delay(1000);
led.RGB(0, 0, 255);
delay(1000);
}
The method RGB is called, but my led don't turn on.
If i move the RGB method to outside of my class, this works fine.
Can someone please tell my what I'm doing worng?
I moved the configuration of pins as OUTPUT to constructor of my class like that:
StatusLED::StatusLED(int pinRed, int pinGreen, int pinBlue) {
this->pinRed = pinRed;
pinMode(pinRed, OUTPUT);
this->pinGreen = pinGreen;
pinMode(pinGreen, OUTPUT);
this->pinBlue = pinBlue;
pinMode(pinBlue, OUTPUT);
RGB(0, 0, 0);
}
This solve the problem.
I also change the method RGB to use analogWrite
as you tell and now the fade is working well too.
void StatusLED::RGB(int redValue, int greenValue, int blueValue) {
if (redValue > 255) {
redValue = 255;
}
if (greenValue > 255) {
greenValue = 255;
}
if (blueValue > 255) {
blueValue = 255;
}
if (redValue < 0) {
redValue = 0;
}
if (greenValue < 0) {
greenValue = 0;
}
if (blueValue < 0) {
blueValue = 0;
}
analogWrite(pinRed, 255 - redValue);
analogWrite(pinGreen, 255 - greenValue);
analogWrite(pinBlue, 255 - blueValue);
}
Thanks everyone!