# 16.01_OPA-输出到IO

## 测试步骤

使能OPA0，内部增益设置为160k:40k，并输出到P2.7。 测试时输入信号固定N端为1V，P端从0.5-1.5V之间线性变化。

## 实测数据

### 输出电压

### 误差

受到测试环境的性能限制，这里的放大倍数和误差仅供参考

## 参考代码

16.01_OPA_Config.c

    /**
     * @brief OPA-输出到IO
     * @details 使能OPA0，内部增益设置为160k:40k，并输出到P2.7。
     * 测试时输入信号固定N端为1V，P端从0.5-1.5V之间线性变化。
     */

    #include "lks32mc09x_opa.h"
    volatile uint32_t opa_out = OPA_OUT_CMP_OUT0P;
    /**
     * @brief 主函数
     */
    int main(void)
    {
        OPA_Enable(OPA_CHANNEL_0);
        OPA_Enable(OPA_CHANNEL_1);
        OPA_Enable(OPA_CHANNEL_2);
        OPA_Enable(OPA_CHANNEL_3);
        OPA_SetGain(OPA_CHANNEL_0, OPA_GAIN_4);
        OPA_OutCmpSignal(OPA_OUT_CMP_OUT0P, 1);
        while (1)
        {
            OPA_OutCmpSignal(opa_out, 1);
        }
    }

## 使用到的库函数

库函数部分代码

    #define OPA_CHANNEL_0 0
    #define OPA_CHANNEL_1 1
    #define OPA_CHANNEL_2 2
    #define OPA_CHANNEL_3 3
    #define SYS0 ((SYS_TypeDef *)(SYS_BASE))

    /**
     * @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通道
     * @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 输出信号选择（使能输出到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;
    }