#include <stdio.h>
#include "LED.h"
#include "esp_log.h"


static const char *LOG_TAG = "LED";

//uint8_t led[6]={0x04,0x20,0x08,0x10,0x02,0x40 };

//uint8_t led[6]={0x20,0x02,0x04,0x08,0x10,0x40 };
//dailiao baoyang tunxing fengcun  guzhang tingji 
uint8_t led[6]={0x04,0x40,0x20,0x10,0x08,0x02 };



#include <stdio.h>

#include "esp_err.h"

static void example_ledc_init(void)
{
    // Prepare and then apply the LEDC PWM timer configuration
    ledc_timer_config_t ledc_timer = {
        .speed_mode       = LEDC_MODE,
        .timer_num        = LEDC_TIMER,
        .duty_resolution  = LEDC_DUTY_RES,
        .freq_hz          = LEDC_FREQUENCY,  // Set output frequency at 5 kHz
        .clk_cfg          = LEDC_AUTO_CLK
    };
    ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));

    // Prepare and then apply the LEDC PWM channel configuration
    ledc_channel_config_t ledc_channel = {
        .speed_mode     = LEDC_MODE,
        .channel        = LEDC_CHANNEL,
        .timer_sel      = LEDC_TIMER,
        .intr_type      = LEDC_INTR_DISABLE,
        .gpio_num       = LEDC_OUTPUT_IO,
        .duty           = 0, // Set duty to 0%
        .hpoint         = 0
    };
    ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
}






void led_init(void)
{

    #if 0
    gpio_config_t led_pin_cfg = {};
    led_pin_cfg.intr_type = GPIO_INTR_DISABLE;
    led_pin_cfg.mode = GPIO_MODE_OUTPUT;
    led_pin_cfg.pin_bit_mask =LED_OUTPUT_PIN_SEL;
    led_pin_cfg.pull_down_en = 0;
    led_pin_cfg.pull_up_en = 1;
    gpio_config(&led_pin_cfg);
    LED_SCLK_0;
    LED_DATA_0;
    LED_LCLK_0;
    LED_RST_0;
    LED_RST_1;
    for(int i=0;i<6;i++)
    led_set(i,0);
    #else

    //void app_main(void)
{
    // Set the LEDC peripheral configuration
    example_ledc_init();
    // Set duty to 50%
    ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 0));
    // Update duty to apply the new value
    ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
}













    #endif

}

static void  _74HC595_WriteByte(unsigned char Byte)
{

    unsigned char i;
    for(i=0;i<8;i++)
    {   
        uint8_t bit = (Byte >> (i)) & 0x01;
        gpio_set_level(LED_DATA_PIN,bit);
        LED_LCLK_0 ;
        LED_LCLK_1 ; 
    }
      LED_SCLK_0;  
      LED_SCLK_1;    
}


void led_set(uint8_t led_index,uint8_t led_status)
{

    ESP_LOGI(LOG_TAG,"led_set  %s",led_status ? "open":"close");

    if(led_status)
    {
        _74HC595_WriteByte(led[led_index]);
    }else
    {
        _74HC595_WriteByte(0x00);
    }
}