I'm new in this forum and in Arduino World. I try to change RGB color with the function analogWrite.
My purpose is to send an array like [X,Y,Z] where {X,Y,Z}={0-255,0-255,0-255} to set the different color in real time with serial port communication using Bluetooth.
I tried to set the intensity color to each color and it's OK, but when I add another color it isn't work
Below I attach my code for only one led...someone can help me?
int ledB=9;
int VarByte;
char VarText;
void setup(){
pinMode(ledB,OUTPUT);
Serial.begin(115200);
}
So you are sending three bytes to go to Red, Green, and Blue PWM channels?
const int ledRpin=3; // Pin number for Red PWM
const int ledGpin=5; // Pin number for Green PWM
const int ledBpin=9; // Pin number for Blue PWM
void setup()
{
pinMode(ledRpin,OUTPUT);
pinMode(ledGpin,OUTPUT);
pinMode(ledBpin,OUTPUT);
Serial.begin(115200);
}
void loop()
{
if (Serial.available() >= 3)
{
analogWrite(ledRpin, Serial.read());
analogWrite(ledGpin, Serial.read());
analogWrite(ledBpin, Serial.read());
}
}
You will have a problem if you EVER miss a byte because you have no indication of start and end of groups of three. Because the three data bytes can be any value it will be hard to add framing without splitting the data values across multiple bytes an putting them back together when received.
Arrays are not referenced by magic. You have to say which element of the array you are using!
int led[]={9,10,11};
int inByte[3];
void setup(){
for(int i=0;i<2;i++){ //// Only two if the three???
pinMode(led,OUTPUT); //// not led[i] ????
Serial.begin(115200);
}
}
void loop(){
if(Serial.available()>0){ /// testing for >0 only allows you to read 1 byte safely. If you read more you might get -1 (no data in buffer)
for(int i=0;i<3;i++){
inByte = Serial.read(); /// not inByte[i] ???
analogWrite(led,inByte); /// not led[i] or inByte[i] ???
}
}
}