1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
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;
}