#include <avr/io.h>
#include "tlc5947.h"

#define	DLED_CHANNELS	24

#define DDR_DLED	DDRD
#define PORT_DLED	PORTD

#define PIN_DLED_CLOCK	5
#define PIN_DLED_DATA	4
#define PIN_DLED_LATCH	6

void init_LED_Drivers(int nb){
    // LED drivers I/O as outputs
    DDR_DLED |= (1<<PIN_DLED_CLOCK) | (1<<PIN_DLED_DATA) | (1<<PIN_DLED_LATCH);
    // Set LATCH output low
    PORT_DLED &= ~(1<<PIN_DLED_LATCH);
}


void set_LED_Drivers(unsigned int pwm[], int nb){
    // Set LATCH output low
    PORT_DLED &= ~(1<<PIN_DLED_LATCH);
    // 24 channels per TLC5947
    int i;
    for(i=DLED_CHANNELS*nb-1; i>=0; i--){
        // 12 bits per channel, send MSB first
        int v=pwm[i];
        int j;
        for(j=0; j<12; j++){
            // Set CLOCK output low
            PORT_DLED &= ~(1<<PIN_DLED_CLOCK);

            // Set DATA as stated by bit #j of i
            if(v & 0x0800)
                PORT_DLED |= (1<<PIN_DLED_DATA);
            else
                PORT_DLED &= ~(1<<PIN_DLED_DATA);

            // Set CLOCK output HIGH
            PORT_DLED |= (1<<PIN_DLED_CLOCK);
            v <<= 1;
        }
    }
    // Set CLOCK output low
    PORT_DLED &= ~(1<<PIN_DLED_CLOCK);

    // Set LATCH output high
    PORT_DLED |= (1<<PIN_DLED_LATCH);
    // Set LATCH output low
    PORT_DLED &= ~(1<<PIN_DLED_LATCH);
}
