Hi. I´m trying to assign a colour to an RGB led throgh an hex number fed through a serial . I´ve been able to get the right values to do so. My problem is that the values of the ints I´m using change in a strange way.
I´m pretty sure the problem is in the control loops, but I cannot find it.
Thank you in advance.
This is my code
byte buffer[7];
int pointer=0;
byte inByte;
int r=0;
int g=0;
int b=0;
int Rled=9;
int Gled=10;
int Bled=11;
void setup(){
Serial.begin(9600);
pinMode(Rled,OUTPUT);
pinMode(Gled,OUTPUT);
pinMode(Bled,OUTPUT);
}
void loop(){
if (Serial.available() > 0) {
Serial.println("A");
Serial.println(r);
Serial.println(g);
Serial.println(b);
while(pointer<6){
inByte = Serial.read();
if(inByte=='#')pointer--;
buffer[pointer]=inByte;
pointer++;
}
Serial.println("B");
Serial.println(r);
Serial.println(g);
Serial.println(b);
pointer=0;
r =hex2dec(buffer[1])+hex2dec(buffer[0])*16;
g=hex2dec(buffer[3])+hex2dec(buffer[2])*16;
b= hex2dec(buffer[5])+ hex2dec(buffer[4])*16;
Serial.println("C");
Serial.println(r);
Serial.println(g);
Serial.println(b);
color(r,g,b);
delay(3000);
}else{
color(255,0,0);
}
}
int hex2dec(byte c){
if(c>='0'&&c<='9'){
return c-'0';
}else if(c>='A'&&c<='F'){
return c-'A'+10;
}
}
void color(int rojo,int verde, int azul){
analogWrite(Rled,255-rojo);
analogWrite(Gled,255-verde);
analogWrite(Bled,255-azul);
}
This is an example
hex fed: #39FF5A. rgb value (57,255,90)
And this is the response
A
0
0
0
B
0
0
0
C
-1054
-1054
-1054
A
-1054
-1054
-1054
B
-1054
-1054
-1054
C
57
255
90