#include "OuterPanel_LED.h"
#include "delay.h"

void LED_Send_CMD(u8 reg,u8 datas){
 
		u8 ack = 0;
		PCA9548_Switch(LED_SWITCH);
		delay_us(200);			
		
    IIC_Start();
    IIC_Send_Byte(LED_ADDR);   
		ack = IIC_Wait_Ack();
    if(ack!=0)
		{
			goto fail;
		}
    IIC_Send_Byte(reg);    
    ack = IIC_Wait_Ack();
    if(ack!=0)
		{
			goto fail;
		}
    IIC_Send_Byte(datas);     //发送字节
    ack = IIC_Wait_Ack();
    if(ack!=0)
		{
			goto fail;
		}
		fail:
		IIC_Stop();//产生一个停止条件
		delay_us(200);
}

void LED_Init(){
		for	(u8 i=1;i<LED_COUNT_MAX+1;i++){
			LED_Send_CMD(i,LED_DEFAULT_VALUE);
		}	
		delay_us(20); 
		GPIO_InitTypeDef  GPIO_InitStructure;

		RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA|RCC_AHB1Periph_GPIOC|RCC_AHB1Periph_GPIOD, ENABLE);//使能GPIO 时钟

		//初始化设置
		GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 ;  
		GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; 
		 
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//推挽输出
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;//50MHz
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;//上拉
		
		GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化
		GPIO_SetBits(GPIOA,GPIO_Pin_11);
		LED_Send_CMD(0,1);
		//LED_ALL(0xAA|1);
		//LED_ALL(0x33|1);
		LED_ALL(0);
		/*for	(u8 i=0;i<LED_COUNT_MAX;i++){
			LED_Send_CMD(LED_CTRL_REG+i,1);
		}	*/
		//GPIO_ResetBits(GPIOA,GPIO_Pin_11);
}
void LED_Refresh(){
		LED_Send_CMD(LED_REFRESH_REG,1);
		delay_us(20); 
}

void LED_Config(u8* datas,u8 len)
{
	for	(u8 i=0;i<len;i++){
		LED_Send_CMD(LED_CTRL_REG+i,datas[i]&1);
		LED_Send_CMD(LED_PWM_REG+i,(datas[i]>>1)*2);
	}	
	LED_Refresh();
}

void LED_ALL(u8 data){
		u8 ledCount = LED_COUNT;
		u8 datas[LED_COUNT];
		for	(u8 i=0;i<LED_COUNT;i++){
					datas[i] = data;
		} 	 
		LED_Config(datas,ledCount);	 
}
