#include "dac_out.h"

void my_dac_init(u8 mode)
{
    clock_gate2_cmd(CLOCK_GATE2_DAC, ENABLE);
    clock_gate0_cmd(CLOCK_GATE0_DAC, ENABLE);

    AUANGCON0 &= ~0x3CE0388;
    AUANGCON0 |= (1 << 3) |
    			 (1 << 9) |
    			 (1 << 17) |
    			 (1 << 18) |
    			 (1 << 19);

    if (mode & DAC_L) {
        AUANGCON0 |= (1 << 8);
        AUANGCON0 |= (1 << 22);
        AUANGCON0 |= (1 << 24);
    }
    if (mode & DAC_R) {
        AUANGCON0 |= (1 << 7);
        AUANGCON0 |= (1 << 23);
        AUANGCON0 |= (1 << 25);
    }

    AUANGCON1 &= ~0xE38004;
    AUANGCON1 |= (1 << 2) |
                 (7 << 21) |
                 (4 << 15);

    AUANGCON2 |= (1 << 6);

    // set analog volume max.
    AUANGCON3 |= 0x70;

    AUANGCON5 |= (63 << 0) |
                 (63 << 8);

    DACDIGCON0 |= (1 << 9) |
                  (1 << 0);

    // block digital volume.
    DACVOLCON = 0;
}

void set_bia_voltage_reg_L(u16 val)
{
    u32 tmp;
    u32 voltage;
    switch(val)
    {
        case 0 ... 100:     voltage = 42525+15*(val);break;
        case 101 ... 300:   voltage = 42525+15*(val);break;
        case 301 ... 500:   voltage = 42465+15*(val);break;
        case 501 ... 800:   voltage = 42435+15*(val);break;
        case 801  ... 1000: voltage = 42375+15*(val);break;
        case 1001 ... 1400: voltage = 42315+15*(val);break;
        case 1401 ... 1800: voltage = 42255+15*(val);break;
        case 1801 ... 2200: voltage = 42195+15*(val);break;
        case 2201 ... 2500: voltage = 42135+15*(val);break;
        case 2501 ... 2800: voltage = 42075+15*(val);break;
        case 2801 ... 3200: voltage = 42015+15*(val);break;
        default:voltage = 42015*(val);break;
    }
    printf("%d ",voltage);
    tmp = DACDCEXP;
    tmp &= ~(uint32_t)(0xffff);
    tmp |= (uint32_t)voltage;
    DACDCEXP = tmp;
    DACRMDCCON |= (1 << 1);
}

void set_bia_voltage_reg_R(u16 val)
{
    u32 tmp;
    u32 voltage;
    switch(val)
    {
        case 0 ... 100:    voltage = 42525+15*(val);break;
        case 101 ... 300:  voltage = 42525+15*(val);break;
        case 301 ... 500:  voltage = 42465+15*(val);break;
        case 501 ... 800:  voltage = 42435+15*(val);break;
        case 801 ... 1000: voltage = 42375+15*(val);break;
        case 1001 ... 1400:voltage = 42465+15*(val);break;
        case 1401 ... 1800:voltage = 42405+15*(val);break;
        case 1801 ... 2200:voltage = 42345+15*(val);break;
        case 2201 ... 2500:voltage = 42285+15*(val);break;
        case 2501 ... 2800:voltage = 42225+15*(val);break;
        case 2801 ... 3200:voltage = 42165+15*(val);break;
        default:voltage = 42165*(val);break;
    }
    printf("%d ",voltage);

    tmp = DACDCEXP;
    tmp &= ~(uint32_t)(0xffff << 16);
    tmp |= (uint32_t)(voltage << 16);
    DACDCEXP = tmp;
    DACRMDCCON |= (1 << 1);
}
// 测试函数
void dac_out_example(void)
{
    set_bia_voltage_reg_L(2000);       //DAC1   无电池最高到2.9V 插上电池能到3.0V
    set_bia_voltage_reg_R(1024);       //DAC0   无电池最高到2.9V 插上电池能到3.0V
}
