#include "lks32mc09x_opa.h"

/**
 * @brief OPA 使能
 * @param OPA_CHANNEL_x OPA通道
 */
void OPA_Enable(uint32_t OPA_CHANNEL_x)
{
    SYS0->PROTECT = 0x7a83;
    switch (OPA_CHANNEL_x)
    {
        case OPA_CHANNEL_0:
            SYS0->AFE_REG1 |= BIT12;
            break;
        case OPA_CHANNEL_1:
            SYS0->AFE_REG1 |= BIT13;
            break;
        case OPA_CHANNEL_2:
            SYS0->AFE_REG1 |= BIT14;
            break;
        case OPA_CHANNEL_3:
            SYS0->AFE_REG1 |= BIT15;
            break;
    }
    SYS0->PROTECT = 0;
}
/**
 * @brief OPA 失能
 * @param OPA_CHANNEL_x OPA通道
 */
void OPA_Disable(uint32_t OPA_CHANNEL_x)
{
    SYS0->PROTECT = 0x7a83;
    switch (OPA_CHANNEL_x)
    {
        case OPA_CHANNEL_0:
            SYS0->AFE_REG1 &= ~BIT12;
            break;
        case OPA_CHANNEL_1:
            SYS0->AFE_REG1 &= ~BIT13;
            break;
        case OPA_CHANNEL_2:
            SYS0->AFE_REG1 &= ~BIT14;
            break;
        case OPA_CHANNEL_3:
            SYS0->AFE_REG1 &= ~BIT15;
            break;
    }
    SYS0->PROTECT = 0;
}
/**
 * @brief OPA 增益设置
 * @param OPA_CHANNEL_x OPA通道
 * @param OPA_GAIN_x OPA增益
 */
void OPA_SetGain(uint32_t OPA_CHANNEL_x, uint32_t OPA_GAIN_x)
{
    SYS0->PROTECT = 0x7a83;
    switch (OPA_CHANNEL_x)
    {
        case OPA_CHANNEL_0:
            SYS0->AFE_REG0 = (SYS0->AFE_REG0 & ~(3)) | OPA_GAIN_x;
            break;
        case OPA_CHANNEL_1:
            SYS0->AFE_REG0 = (SYS0->AFE_REG0 & ~(3 << 2)) | (OPA_GAIN_x << 2);
            break;
        case OPA_CHANNEL_2:
            SYS0->AFE_REG0 = (SYS0->AFE_REG0 & ~(3 << 4)) | (OPA_GAIN_x << 4);
            break;
        case OPA_CHANNEL_3:
            SYS0->AFE_REG0 = (SYS0->AFE_REG0 & ~(3 << 6)) | (OPA_GAIN_x << 6);
            break;
    }
    SYS0->PROTECT = 0;
}
/**
 * @brief OPA 偏置电流设置
 * @param OPA_IT_x OPA偏置电流
 */
void OPA_SetIt(uint32_t OPA_IT_x)
{
    SYS0->PROTECT  = 0x7a83;
    SYS0->AFE_REG0 = (SYS0->AFE_REG0 & ~(3 << 8)) | (OPA_IT_x << 8);
    SYS0->PROTECT  = 0;
}
/**
 * @brief OPA 输出信号选择（使能输出到GPIO）
 * @param OPA_OUT_CMP_x OPA_OUT_CMP信号来源配置
 * @param Out2Gpio OPA_OUT_CMP输出到IO使能，P2.7
 */
void OPA_OutCmpSignal(uint32_t OPA_OUT_CMP_x, uint32_t Out2Gpio)
{
    SYS0->PROTECT  = 0x7a83;
    SYS0->AFE_REG2 = (SYS0->AFE_REG2 & ~(0xf)) |
                     (OPA_OUT_CMP_x) |
                     (Out2Gpio << 3);
    SYS0->PROTECT = 0;
}
