simulate this circuit – Schematic created using CircuitLab
Its a simple project. I am trying to drive 3 RGB LEDs using Arduino Nano. Since Arduino Nano does not have 9 PWM pins, the only solution I can think of by multiplexing them. I have try multiplexing 12 7-segments driven by atmega16, the results was satisfying. Is it possible to do PWM multiplexing on Arduino Nano?
So far, here is what I have done:
const int R=9, G=10, B=11, M1=5, M2=6, M3=7;
//I use pin 5,6,7 as selector since they are on same PORT (PORTD)
void setup()
{
pinMode (R,OUTPUT);
pinMode (G,OUTPUT);
pinMode (B,OUTPUT);
pinMode (M1,OUTPUT);
pinMode (M2,OUTPUT);
pinMode (M3,OUTPUT);
}
void led(int r, int g, int b)
{
analogWrite(R,255-r);
analogWrite(G,255-g);
analogWrite(B,255-b);
}
void loop()
{
for(int i=0; i<256; i++)
{
led(0,0,i);
__asm__("nop\n\t"); //one clock cycle delay
PORTD = B10000000; //select LED-1
led(0,i,0);
__asm__("nop\n\t"); //one clock cycle delay
PORTD = B01000000; //select LED-2
led(i,0,0);
__asm__("nop\n\t"); //one clock cycle delay
PORTD = B00100000; //select LED-3
}
for(int i=256; i>0; i--)
{
led(0,0,i);
__asm__("nop\n\t"); //one clock cycle delay
PORTD = B10000000; //select LED-1
led(0,i,0);
__asm__("nop\n\t"); //one clock cycle delay
PORTD = B01000000; //select LED-2
led(i,0,0);
__asm__("nop\n\t"); //one clock cycle delay
PORTD = B00100000; //select LED-3
}
}
But still, this does not work. The result is all the led turned on, with 'a little bit' different color, mainly white with a little addition of another color (while it supposed to be contrast, R, G and B for each LED), and its blinking. The blink is very short, but still, its annoying. One possibility I can think of my code still not optimum.
Someone had an idea?
EDIT
I fixed the diagram, I hope the diagram does not make any misunderstandings. As the suggestion from @jwpat7, I forget to inform that the led still error even if there is just one for-loop
.
I am using __asm__("nop\n\t")
as delay substitution because "theoretically", 1 clock cycle from 16mHz clock is shorter than 1 microseconds. (correct me if I am wrong, but I think its about 62.5 ns)
Thanks in advance