chen
2024-11-08 cc432b761c884a0bd8e9d83db0a4e26109fc08b1
keil/include/drivers/mk_adc.c
对比新文件
@@ -0,0 +1,497 @@
/*
 * Copyright (c) 2019-2023 Beijing Hanwei Innovation Technology Ltd. Co. and
 * its subsidiaries and affiliates (collectly called MKSEMI).
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into an MKSEMI
 *    integrated circuit in a product or a software update for such product,
 *    must reproduce the above copyright notice, this list of conditions and
 *    the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of MKSEMI nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    MKSEMI integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be
 *    reverse engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY MKSEMI "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL MKSEMI OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "mk_adc.h"
#include "mk_clock.h"
#include "mk_reset.h"
#include "mk_trace.h"
#include "mk_misc.h"
#if ADC_DMA_MODE_EN
static void adc_dma_callback(void *ch, uint32_t err_code);
#endif
static struct ADC_HANDLE_T adc_handle = {
    .base = ADC,
    .irq = ADC_IRQn,
    .dma_ch = DMA_CH1,
    .callback = NULL,
};
int adc_open(struct ADC_CFG_T *config)
{
    if (config == NULL)
    {
        return DRV_ERROR;
    }
    // check if ADC is using by HW or not
    if (adc_handle.base->STATUS & ADC_STATUS_BUSY_MSK)
    {
        return DRV_BUSY;
    }
    else
    {
        // enable ADC clock
        clock_enable(CLOCK_ADC);
        reset_module(RESET_MODULE_ADC);
    }
    adc_handle.mode = config->mode;
    adc_handle.int_en = config->int_en;
    adc_handle.dma_en = config->dma_en;
    adc_handle.base->CTRL0 = ADC_CTRL0_CONV_MODE(adc_handle.mode) | ADC_CTRL0_CLK_SEL(config->clk_sel) | ADC_CTRL0_CHNL_P(config->channel_p) |
                             ADC_CTRL0_CHNL_N(config->channel_n) | ADC_CTRL0_ACC_NUM(config->acc_num) | ADC_CTRL0_HIGH_PULSE_WIDTH(config->high_pulse_time) |
                             ADC_CTRL0_SETTLE_TIME(config->settle_time);
    uint32_t adc_clk = config->clk_sel ? ADC_CLK_LOW_FREQ : ADC_CLK_HIGH_FREQ;
    /* If the sampling rate setting exceeds the conversion rate threshold, the maximum sampling rate is used by default */
    uint32_t rate = (adc_clk == ADC_CLK_LOW_FREQ) ? ((config->rate < ADC_CLK_L_MAX_SAMPLE_RATE) ? config->rate : ADC_CLK_L_MAX_SAMPLE_RATE)
                        : (config->rate < ADC_CLK_H_MAX_SAMPLE_RATE ? config->rate : ADC_CLK_H_MAX_SAMPLE_RATE);
    /* If the sample rate is set to 0, no frequency division */
    uint16_t div = (uint16_t)((adc_clk / ((rate == 0) ? 1 : rate)) - 1);
    adc_handle.base->CTRL1 = ADC_CTRL1_CONV_RATE(div);
    // TS_VS
    uint32_t val = REG_READ(0x4000062C);
    if (config->vref_sel == ADC_SEL_VREF_INT)
    {
        val &= ~(1U << 8);
        val |= (1 << 9) | (7 << 5) | (1 << 4);
    }
    else
    {
        val |= (1 << 8);
        /* If the external reference voltage driving capability is insufficient */
        /* It is recommended to enable this configuration */
        // val |= (9 << 1) | (1 << 4);
    }
    REG_WRITE(0x4000062C, val);
    if (adc_handle.dma_en)
    {
        // enable DMA
        adc_handle.base->DMA_EN = ADC_DMA_EN_MSK;
    }
    else if (adc_handle.int_en)
    {
        NVIC_SetPriority(adc_handle.irq, IRQ_PRIORITY_NORMAL);
        NVIC_ClearPendingIRQ(adc_handle.irq);
        NVIC_EnableIRQ(adc_handle.irq);
    }
    adc_handle.state = ADC_STATE_READY;
    return DRV_OK;
}
int adc_close(void)
{
    // check if ADC is using by HW or not
    if ((adc_handle.base->STATUS & ADC_STATUS_BUSY_MSK) && (adc_handle.state != ADC_STATE_BUSY))
    {
        return DRV_BUSY;
    }
    else
    {
        // disable conversion
        adc_handle.base->CTRL2 &= ~ADC_CTRL2_CONV_EN_MSK;
    }
    if (adc_handle.int_en)
    {
        NVIC_DisableIRQ(adc_handle.irq);
        NVIC_ClearPendingIRQ(adc_handle.irq);
    }
    // disable ADC clock
    clock_disable(CLOCK_ADC);
    // update status
    adc_handle.state = ADC_STATE_RESET;
    return DRV_OK;
}
int adc_switch_channel(enum ADC_P_N_SET P, enum ADC_P_N_SET N)
{
    if (adc_handle.state == ADC_STATE_BUSY)
    {
        return DRV_BUSY;
    }
    adc_handle.base->CTRL0 = (adc_handle.base->CTRL0 & ~(ADC_CTRL0_CHNL_P_MSK | ADC_CTRL0_CHNL_N_MSK)) | ADC_CTRL0_CHNL_P(P) | ADC_CTRL0_CHNL_N(N);
    return DRV_OK;
}
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
int adc_get(uint32_t *data, uint16_t number, drv_callback_t callback)
{
    uint32_t lock = int_lock();
    // update state
    switch (adc_handle.state)
    {
    case ADC_STATE_READY:
        adc_handle.state = ADC_STATE_BUSY;
        break;
    case ADC_STATE_BUSY:
        int_unlock(lock);
        return DRV_BUSY;
    case ADC_STATE_RESET:
    case ADC_STATE_TIMEOUT:
    case ADC_STATE_ERROR:
        int_unlock(lock);
        return DRV_ERROR;
    }
    adc_handle.data = data;
    adc_handle.number = number;
    adc_handle.count = number;
    adc_handle.callback = callback;
    int_unlock(lock);
    if (adc_handle.dma_en)
    {
#if ADC_DMA_MODE_EN
        struct DMA_CH_CFG_T adc_dma_cfg = {
            .fifo_th = DMA_FIFO_TH_4,
            .src_burst_size = DMA_SRC_BURST_SIZE_4,
            .src_width = DMA_WIDTH_4B,
            .dst_width = DMA_WIDTH_4B,
            .src_addr_ctrl = DMA_ADDR_FIXED,
            .dst_addr_ctrl = DMA_ADDR_INC,
            .src_req_sel = DMA_REQ_ADC,
            .dst_req_sel = DMA_REQ_MEM,
        };
        dma_open(adc_handle.dma_ch, &adc_dma_cfg);
        dma_transfer(adc_handle.dma_ch, (uint32_t *)&adc_handle.base->DATA, data, number, adc_dma_callback);
        // start conversion
        adc_handle.base->CTRL2 = ADC_CTRL2_CONV_EN_MSK;
#endif
    }
    else if (adc_handle.int_en)
    {
#if ADC_INT_MODE_EN
        // enable interrupt
        adc_handle.base->INTR_EN = ADC_INTR_DONE_EN_MSK | ADC_INTR_CONFLICT_EN_MSK | ADC_INTR_OVERWRITE_EN_MSK;
        // start conversion
        adc_handle.base->CTRL2 = ADC_CTRL2_CONV_EN_MSK;
#endif
    }
    else
    {
#if ADC_POLL_MODE_EN
        // polling
        while (adc_handle.count > 0)
        {
            if (adc_handle.mode == ADC_MODE_SINGLE)
            {
                // start conversion
                adc_handle.base->CTRL2 = ADC_CTRL2_CONV_EN_MSK;
            }
            else if ((adc_handle.mode == ADC_MODE_CONTINUE) && (adc_handle.count == adc_handle.number))
            {
                // start conversion
                adc_handle.base->CTRL2 = ADC_CTRL2_CONV_EN_MSK;
            }
            while ((adc_handle.base->STATUS & ADC_STATUS_DONE_MSK) == 0)
            {
            }
            *adc_handle.data++ = adc_handle.base->DATA;
            adc_handle.count--;
        }
        if (adc_handle.mode == ADC_MODE_CONTINUE)
        {
            adc_handle.base->CTRL2 &= ~ADC_CTRL2_CONV_EN_MSK;
        }
        // update state
        adc_handle.state = ADC_STATE_READY;
        if (adc_handle.callback)
        {
            adc_handle.callback(adc_handle.data - adc_handle.number, adc_handle.number);
        }
#endif
    }
    return DRV_OK;
}
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#if ADC_DMA_MODE_EN
static void adc_dma_callback(void *ch, uint32_t err_code)
{
    uint8_t ch_num = *(uint8_t *)ch;
    if (ch_num == adc_handle.dma_ch)
    {
        if (adc_handle.mode == ADC_MODE_CONTINUE)
        {
            // stop conversion
            adc_handle.base->CTRL2 &= ~ADC_CTRL2_CONV_EN_MSK;
        }
        if (err_code == DMA_INT_TYPE_DONE)
        {
            // finished - update statue
            adc_handle.state = ADC_STATE_READY;
        }
        else
        {
            adc_handle.state = ADC_STATE_ERROR;
        }
        if (adc_handle.callback)
        {
            adc_handle.callback(adc_handle.data, adc_handle.number);
        }
    }
    else
    {
        ASSERT(0, "Unexpected dma channel\r\n");
    }
}
#endif
void ADC_IRQHandler(void)
{
#if ADC_INT_MODE_EN
    uint32_t int_stat = adc_handle.base->INTR_STATUS;
    if (int_stat & ADC_INTR_STATUS_CONFLICT_MSK)
    {
        adc_handle.state = ADC_STATE_ERROR;
        adc_handle.base->INTR_CLR = ADC_INTR_CONFLICT_CLR_MSK;
    }
    else if (int_stat & ADC_INTR_STATUS_OVERWRITE_MSK)
    {
        adc_handle.state = ADC_STATE_ERROR;
        adc_handle.base->INTR_CLR = ADC_INTR_OVERWRITE_CLR_MSK;
    }
    else if (int_stat & ADC_INTR_STATUS_DONE_MSK)
    {
        if (adc_handle.count)
        {
            *adc_handle.data++ = adc_handle.base->DATA;
            adc_handle.count--;
        }
        if (adc_handle.count)
        {
            // continue
            if (adc_handle.mode == ADC_MODE_SINGLE)
            {
                adc_handle.base->CTRL2 = ADC_CTRL2_CONV_EN_MSK;
            }
        }
        else
        {
            // done
            if (adc_handle.mode == ADC_MODE_CONTINUE)
            {
                // stop conversion
                adc_handle.base->CTRL2 &= ~ADC_CTRL2_CONV_EN_MSK;
                adc_handle.base->INTR_CLR = ADC_INTR_DONE_CLR_MSK;
                // clear pending interrupt
                NVIC_ClearPendingIRQ(adc_handle.irq);
            }
            // finished - update status
            adc_handle.state = ADC_STATE_READY;
            if (adc_handle.callback)
            {
                adc_handle.callback(adc_handle.data - adc_handle.number, adc_handle.number);
            }
        }
    }
    else
    {
        ASSERT(0, "Unexpected ADC interrupt\r\n");
    }
#endif
}
int16_t adc_code_to_mv(int16_t adc_val, int16_t vref_mv)
{
    int16_t val = adc_val;
    if (adc_val >= 0x800)
    {
        val = adc_val - 0x1000;
    }
    float vol = val * vref_mv / (2048);
    return (int16_t)vol;
}
/* BATTM (battery monitor == voltage sensor) */
void battery_monitor_open(void)
{
    // enable ADC
    struct ADC_CFG_T vs_adc_cfg;
    vs_adc_cfg.mode = ADC_MODE_CONTINUE;    /* Selected single conversion mode  */
    vs_adc_cfg.clk_sel = ADC_CLK_HIGH;      /* Selected 62.4M high speed clock */
    vs_adc_cfg.vref_sel = ADC_SEL_VREF_INT; /* Using internal reference voltage (1.2V)*/
    vs_adc_cfg.rate = 1000;                 /* ADC works at high frequency system clock, the maximum sampling rate is 2M */
    vs_adc_cfg.channel_p = 7;               /* ADC positive channel --> VDD/4 */
    vs_adc_cfg.channel_n = 2;               /* ADC negative channel --> GND */
    vs_adc_cfg.int_en = false;
    vs_adc_cfg.dma_en = false; /* DMA support only in continue mode */
    vs_adc_cfg.acc_num = 0;
    vs_adc_cfg.high_pulse_time = 4;
    vs_adc_cfg.settle_time = 1;
    adc_open(&vs_adc_cfg);
    // enable BATTM
    adc_handle.base->CTRL1 |= ADC_CTRL1_VS_EN_MSK;
}
void battery_monitor_close(void)
{
    // disable BATTM
    adc_handle.base->CTRL1 &= ~ADC_CTRL1_VS_EN_MSK;
    adc_close();
}
static void adc_continue_callback(void *data, uint32_t number)
{
    LOG_INFO(TRACE_MODULE_APP, "Chip adc callback %d degree\r\n", data);
}
int16_t battery_monitor_get(void)
{
#define NUM_SAMPLES (3)
    uint32_t sample[NUM_SAMPLES];
    adc_get(&sample[0], NUM_SAMPLES, adc_continue_callback);
    int32_t sum = 0;
    for (int i = 0; i < NUM_SAMPLES; i++)
    {
        sum += adc_code_to_mv((int16_t)sample[i], ADC_INTERNAL_VREF_MV);
    }
    return (int16_t)(4 * sum / NUM_SAMPLES);
}
/* TEMP (temperature sensor)*/
void temp_sensor_open(void)
{
    // enable ADC
    struct ADC_CFG_T ts_adc_cfg;
    ts_adc_cfg.mode = ADC_MODE_SINGLE;      /* Selected single conversion mode  */
    ts_adc_cfg.clk_sel = ADC_CLK_HIGH;      /* Selected 62.4M high speed clock */
    ts_adc_cfg.vref_sel = ADC_SEL_VREF_INT; /* Using internal reference voltage (1.2V)*/
    ts_adc_cfg.rate = 1000;                 /* ADC works at high frequency system clock, the maximum sampling rate is 2M */
    ts_adc_cfg.channel_p = 3;               /* ADC positive channel --> Vref */
    ts_adc_cfg.channel_n = 4;               /* ADC negative channel --> Temp sensor */
    ts_adc_cfg.int_en = false;
    ts_adc_cfg.dma_en = false; /* DMA support only in continue mode */
    ts_adc_cfg.acc_num = 0;
    ts_adc_cfg.high_pulse_time = 4;
    ts_adc_cfg.settle_time = 1;
    adc_open(&ts_adc_cfg);
    // enable TEMP
    adc_handle.base->CTRL1 |= ADC_CTRL1_TS_EN_MSK;
    delay_us(100);
}
void temp_sensor_close(void)
{
    // disable TEMP
    adc_handle.base->CTRL1 &= ~ADC_CTRL1_TS_EN_MSK;
    adc_close();
}
int8_t temp_sensor_get(int16_t *p_adc_value)
{
#define NUM_SAMPLES (3)
    uint32_t sample[NUM_SAMPLES];
    adc_get(&sample[0], NUM_SAMPLES, NULL);
    uint32_t reg_value = REG_READ(0x40000300);
    int16_t temp_ref_code = reg_value & 0xfff;
    int8_t temp_ref_val = (int8_t)((reg_value >> 12) & 0xFF);
    float temp_ref_val_f = temp_ref_val == 0 ? 25 : (float)(temp_ref_val >> 2) + (float)(temp_ref_val & 0x03) * 0.25f;
    int32_t sum = 0;
    for (int i = 0; i < NUM_SAMPLES; i++)
    {
        sum += sample[i];
    }
    int16_t temp_code = (int16_t)(sum / NUM_SAMPLES);
    int8_t temp_val = 0;
    if ((temp_ref_code > 600) && (temp_ref_code < 1400))
    {
        temp_val = (int8_t)(ADC_TEMP_K_FACTOR * (temp_code - temp_ref_code) + 0.5 + temp_ref_val_f);
    }
    else
    {
        // y = 0.3449x - 299.92
        temp_val = (int8_t)(ADC_TEMP_K_FACTOR * temp_code - 299.42);
    }
    if (p_adc_value)
        *p_adc_value = temp_code;
    return temp_val;
}