#include "main.h"

  //__ASM("NOP");
  // pd0 - sdi (Serial-data input to the shift register)
  // pd1 - dclk (Clock input terminal used to shift data on rising edge and carries command information when LE is asserted.)
  // pd2 - le (Data strobe terminal and controlling command with DCLK)
  // pd3 - gclk (Gray scale clock terminal Clock input for gray scale. The gray scale display is counted by gray scale clock comparing with input data.)
  const unsigned int sdi = 0;
  const unsigned int dclk = 1;
  const unsigned int le = 2;
  const unsigned int gclk = 3;

#define	MBI_DATA_LATCH		1 
#define	MBI_GLOBAL_LATCH	3 
#define	MBI_READ_CONFIG		5 
#define	MBI_ENABLE_ERR_DETECT	7 
#define	MBI_READ_ERR_STATUS		9 
#define	MBI_WRITE_CONFIG		11 
// const uint16_t led_arr[16] = {0x1234,0x2345,0x3456,0x4567,0x5678,0x6789,0x7890,0x8901,0x9012,0x0123,0x0000,0x1111,0x2222,0x3333,0x4444,0x5555};;

int main(void)
{
  unsigned int i;
  //unsigned int sdi, dclk, le, gclk;

  GPIO_InitTypeDef GPIO_InitStructure;
  uint16_t led_arr[16];
	
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  //GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
  GPIO_Init(GPIOD, &GPIO_InitStructure);

  GPIOD->ODR = 0;

  for(i=0; i<16;i++)
    led_arr[i]=0x1<<i;	
  for(i=0; i<15;i++)
  {
    MBI_write(led_arr[i], MBI_DATA_LATCH);
  }
  MBI_write(led_arr[i], MBI_GLOBAL_LATCH);

  while(1)
  {
    //gclk
    GPIOD->BSRR = 1<<gclk;//on
    GPIOD->BRR = 1<<gclk;//off
  }
}

void MBI_write(unsigned int DATA, unsigned char MODE)
{
  unsigned char i;
  unsigned int temp;
  for(i=0; i<16; i++)
  {
    temp = DATA&(0x01<<i);
    //if( ( (led_arr[i] >> j) & 0x1) == 1)
    if(temp)
      GPIOD->BSRR = 1<<sdi;//sdi on
    else
      GPIOD->BRR = 1<<sdi;//sdi off
    if(i>(15 - MODE))
    {
       GPIOD->BSRR = 1<<le;//le on
    }
    GPIOD->BSRR = 1<<dclk;//dclk on
    GPIOD->BRR = 1<<dclk;//dclk off
  }
  GPIOD->BRR = 1<<le;//le off
}   

void MBI_WriteConfig(unsigned int config, unsigned char len) {   
    unsigned char i;   
    for(i=0;i <(len-1);i++) {   
        MBI_write(config,MBI_DATA_LATCH);      
    }      
    MBI_write(config,MBI_WRITE_CONFIG);    
}      
