#include <avr/io.h>

#include "tlc5947.h"

#define DDR_DLED_CLOCK	DDRE
#define PORT_DLED_CLOCK	PORTE

#define DDR_DLED_DATA	DDRG
#define PORT_DLED_DATA	PORTG

#define DDR_DLED_LATCH	DDRB
#define PORT_DLED_LATCH	PORTB

#define PIN_DLED_CLOCK	0x08
#define PIN_DLED_DATA	0x20
#define PIN_DLED_LATCH	0x10

void init_LED_Drivers(int nb){
    // LED drivers I/O as outputs
    DDR_DLED_CLOCK |= PIN_DLED_CLOCK;
    DDR_DLED_DATA |= PIN_DLED_DATA;
    DDR_DLED_LATCH |= PIN_DLED_LATCH;
    // Set LATCH output low
    PORT_DLED_LATCH &= ~PIN_DLED_LATCH;
}


void set_LED_Drivers(unsigned int pwm[], int nb){
    // Set LATCH output low
    PORT_DLED_LATCH &= ~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_CLOCK &= ~PIN_DLED_CLOCK;

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

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

    // Set LATCH output high
    PORT_DLED_LATCH |= PIN_DLED_LATCH;
    // Set LATCH output low
    PORT_DLED_LATCH &= ~PIN_DLED_LATCH;
}
