1 /***************************************************************************//**
2  * @file
3  * @brief Incremental Analog to Digital Converter (IADC) Peripheral API
4  *******************************************************************************
5  * # License
6  * <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
7  *******************************************************************************
8  *
9  * SPDX-License-Identifier: Zlib
10  *
11  * The licensor of this software is Silicon Laboratories Inc.
12  *
13  * This software is provided 'as-is', without any express or implied
14  * warranty. In no event will the authors be held liable for any damages
15  * arising from the use of this software.
16  *
17  * Permission is granted to anyone to use this software for any purpose,
18  * including commercial applications, and to alter it and redistribute it
19  * freely, subject to the following restrictions:
20  *
21  * 1. The origin of this software must not be misrepresented; you must not
22  *    claim that you wrote the original software. If you use this software
23  *    in a product, an acknowledgment in the product documentation would be
24  *    appreciated but is not required.
25  * 2. Altered source versions must be plainly marked as such, and must not be
26  *    misrepresented as being the original software.
27  * 3. This notice may not be removed or altered from any source distribution.
28  *
29  ******************************************************************************/
30 
31 #include "em_iadc.h"
32 
33 #if defined(IADC_COUNT) && (IADC_COUNT > 0)
34 
35 #include "sl_assert.h"
36 #include "em_cmu.h"
37 #include "sl_common.h"
38 #include <stddef.h>
39 
40 /***************************************************************************//**
41  * @addtogroup emlib
42  * @{
43  ******************************************************************************/
44 
45 /***************************************************************************//**
46  * @addtogroup iadc IADC - Incremental ADC
47  * @brief Incremental Analog to Digital Converter (IADC) Peripheral API
48  * @details
49  *  This module contains functions to control the IADC peripheral of Silicon
50  *  Labs 32-bit MCUs and SoCs. The IADC is used to convert analog signals into a
51  *  digital representation.
52  * @{
53  ******************************************************************************/
54 
55 /*******************************************************************************
56  *******************************   DEFINES   ***********************************
57  ******************************************************************************/
58 
59 /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */
60 
61 // Validation of IADC register block pointer reference for assert statements.
62 #if defined(IADC_NUM)
63 #define IADC_REF_VALID(ref)    (IADC_NUM(ref) != -1)
64 #else
65 #if (IADC_COUNT == 1)
66 #define IADC_REF_VALID(ref)    ((ref) == IADC0)
67 #define IADC_NUM(ref)          (((ref) == IADC0) ? 0 : -1)
68 #elif (IADC_COUNT == 2)
69 #define IADC_REF_VALID(ref)    (((ref) == IADC0) || ((ref) == IADC1))
70 #define IADC_NUM(ref)          (((ref) == IADC0) ? 0 : ((ref) == IADC1) ? 1 : -1)
71 #endif
72 #endif
73 
74 // Max IADC clock rates
75 #define IADC_CLK_MAX_FREQ                   40000000UL
76 #define IADC_ANA_CLK_HIGH_SPEED_MAX_FREQ    20000000UL
77 #define IADC_ANA_CLK_NORMAL_MAX_FREQ        10000000UL
78 #define IADC_ANA_CLK_HIGH_ACCURACY_MAX_FREQ  5000000UL
79 #if defined (_IADC_CFG_ADCMODE_HIGHSPEED)
80 #define IADC_ANA_CLK_MAX_FREQ(adcMode) (                          \
81     (adcMode) == iadcCfgModeNormal ? IADC_ANA_CLK_NORMAL_MAX_FREQ \
82     : ((adcMode) == iadcCfgModeHighSpeed                          \
83        ? IADC_ANA_CLK_HIGH_SPEED_MAX_FREQ                         \
84        : IADC_ANA_CLK_HIGH_ACCURACY_MAX_FREQ)                     \
85     )
86 #else
87 #define IADC_ANA_CLK_MAX_FREQ(adcMode) (                          \
88     (adcMode) == iadcCfgModeNormal ? IADC_ANA_CLK_NORMAL_MAX_FREQ \
89     : IADC_ANA_CLK_HIGH_ACCURACY_MAX_FREQ                         \
90     )
91 #endif
92 
93 #define IADC_ROUND_D2I(n) (int)((n) < 0.0f ? ((n) - 0.5f) : ((n) + 0.5f))
94 
95 #define IADC0_SCANENTRIES IADC0_ENTRIES
96 #define IADC0_FIFOENTRIES 0x4UL
97 
98 #define IADC1_SCANENTRIES IADC1_ENTRIES
99 #define IADC1_FIFOENTRIES 0x4UL
100 
101 #if defined(IADC_ENTRIES)
102 #define IADC_SCANENTRIES(iadc) IADC_ENTRIES(IADC_NUM(iadc))
103 #else
104 #define IADC_SCANENTRIES(iadc) (        \
105     (iadc) == IADC0 ? IADC0_SCANENTRIES \
106     : 0UL)
107 #endif
108 
109 #if !defined(IADC_CONFIGNUM)
110 #define IADC_CONFIGNUM(iadc) (    \
111     (iadc) == 0 ? IADC0_CONFIGNUM \
112     : 0UL)
113 #endif
114 
115 #define IADC_FIFOENTRIES(iadc) (        \
116     (iadc) == IADC0 ? IADC0_FIFOENTRIES \
117     : 0UL)
118 
119 #define IADC_CMU_CLOCK(iadc) (       \
120     (iadc) == IADC0 ? cmuClock_IADC0 \
121     : cmuClock_IADC0)
122 
123 /** @endcond */
124 
125 /*******************************************************************************
126  ***************************   LOCAL FUNCTIONS   *******************************
127  ******************************************************************************/
128 
129 /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */
130 
IADC_disable(IADC_TypeDef * iadc)131 static void IADC_disable(IADC_TypeDef *iadc)
132 {
133 #if defined(IADC_STATUS_SYNCBUSY)
134   while ((iadc->STATUS & IADC_STATUS_SYNCBUSY) != 0U) {
135     // Wait for synchronization to finish before disable
136   }
137 #endif
138   iadc->EN_CLR = IADC_EN_EN;
139 #if defined(_IADC_EN_DISABLING_MASK)
140   while (IADC0->EN & _IADC_EN_DISABLING_MASK) {
141   }
142 #endif
143 }
144 
IADC_enable(IADC_TypeDef * iadc)145 static void IADC_enable(IADC_TypeDef *iadc)
146 {
147   iadc->EN_SET = IADC_EN_EN;
148 }
149 
IADC_ConvertRawDataToResult(uint32_t rawData,IADC_Alignment_t alignment)150 static IADC_Result_t IADC_ConvertRawDataToResult(uint32_t rawData,
151                                                  IADC_Alignment_t alignment)
152 {
153   IADC_Result_t result;
154 
155   switch (alignment) {
156     case iadcAlignRight12:
157 #if defined(IADC_SINGLEFIFOCFG_ALIGNMENT_RIGHT16)
158     case iadcAlignRight16:
159 #endif
160 #if defined(IADC_SINGLEFIFOCFG_ALIGNMENT_RIGHT20)
161     case iadcAlignRight20:
162 #endif
163       // Mask out ID and replace with sign extension
164       result.data = (rawData & 0x00FFFFFFUL)
165                     | ((rawData & 0x00800000UL) != 0x0UL ? 0xFF000000UL : 0x0UL);
166       // Mask out data and shift down
167       result.id   = (uint8_t)((rawData & 0xFF000000UL) >> 24);
168       break;
169 
170     case iadcAlignLeft12:
171 #if defined(IADC_SINGLEFIFOCFG_ALIGNMENT_RIGHT16)
172     case iadcAlignLeft16:
173 #endif
174 #if defined(IADC_SINGLEFIFOCFG_ALIGNMENT_RIGHT20)
175     case iadcAlignLeft20:
176 #endif
177       result.data = rawData & 0xFFFFFF00UL;
178       result.id   = (uint8_t)(rawData & 0x000000FFUL);
179       break;
180     default:
181       break;
182   }
183   return result;
184 }
185 
186 /** @endcond */
187 
188 /*******************************************************************************
189  **************************   GLOBAL FUNCTIONS   *******************************
190  ******************************************************************************/
191 
192 /***************************************************************************//**
193  * @brief
194  *   Initialize IADC.
195  *
196  * @details
197  *   Initializes common parts for both single conversion and scan sequence.
198  *   In addition, single and/or scan control configuration must be done, please
199  *   refer to @ref IADC_initSingle() and @ref IADC_initScan() respectively.
200  *
201  * @note
202  *   This function will stop any ongoing conversions.
203  *
204  * @param[in] iadc
205  *   Pointer to IADC peripheral register block.
206  *
207  * @param[in] init
208  *   Pointer to IADC initialization structure.
209  *
210  * @param[in] allConfigs
211  *   Pointer to structure holding all configs.
212  ******************************************************************************/
IADC_init(IADC_TypeDef * iadc,const IADC_Init_t * init,const IADC_AllConfigs_t * allConfigs)213 void IADC_init(IADC_TypeDef *iadc,
214                const IADC_Init_t *init,
215                const IADC_AllConfigs_t *allConfigs)
216 {
217   uint32_t tmp;
218   uint32_t config;
219   uint16_t wantedPrescale;
220   uint8_t srcClkPrescale;
221   uint32_t adcClkPrescale;
222   uint8_t timebase;
223   unsigned uiAnaGain;
224   uint16_t uiGainCAna;
225   IADC_CfgAdcMode_t adcMode;
226 #if defined(_IADC_CFG_ADCMODE_HIGHACCURACY)
227   float anaGain;
228   int anaGainRound;
229   float offsetAna;
230   float offset2;
231   int offsetLong;
232   int offsetAna1HiAccInt;
233   uint8_t osrValue;
234   float offsetAnaBase;
235   float gainSysHiAcc;
236   float refVoltage = 0;
237   // Over sampling ratio for high accuracy conversions
238   const float osrHiAcc[6] = { 16.0, 32.0, 64.0, 92.0, 128.0, 256.0 };
239 #endif
240 
241   EFM_ASSERT(IADC_REF_VALID(iadc));
242 
243   // Calculate min allowed SRC_CLK prescaler setting
244   srcClkPrescale = IADC_calcSrcClkPrescale(iadc, IADC_CLK_MAX_FREQ, 0);
245 
246   wantedPrescale = init->srcClkPrescale;
247   // Use wanted SRC_CLK prescaler setting instead if it is high enough
248   if (wantedPrescale >= srcClkPrescale) {
249     srcClkPrescale = wantedPrescale;
250   }
251 
252   IADC_disable(iadc);
253 
254   timebase = init->timebase;
255   if (timebase == 0) {
256     // CLK_SRC_ADC is derived from CLK_CMU_ADC, and must be no faster than 40 MHz. Therefore we set
257     // srcClkFreq's original value to CLK_CMU_ADC before evaluating the prescaling conditions.
258     uint32_t srcClkFreq = CMU_ClockFreqGet(cmuClock_IADC0);
259     // If srcClkFreq is greater than 40MHz, then divide by the prescaler HSCLKRATE to obtain valid frequency
260     if (srcClkFreq >= IADC_CLK_MAX_FREQ) {
261       srcClkFreq = srcClkFreq / srcClkPrescale;
262     }
263     // Calculate timebase based on CMU_IADCCLKCTRL
264     timebase = IADC_calcTimebase(iadc, srcClkFreq);
265   }
266 
267   tmp = (((uint32_t)(init->warmup) << _IADC_CTRL_WARMUPMODE_SHIFT)
268          & _IADC_CTRL_WARMUPMODE_MASK)
269         | (((uint32_t)(timebase) << _IADC_CTRL_TIMEBASE_SHIFT)
270            & _IADC_CTRL_TIMEBASE_MASK)
271         | (((uint32_t)(srcClkPrescale) << _IADC_CTRL_HSCLKRATE_SHIFT)
272            & _IADC_CTRL_HSCLKRATE_MASK);
273 
274   if (init->iadcClkSuspend0) {
275     tmp |= IADC_CTRL_ADCCLKSUSPEND0;
276   }
277   if (init->iadcClkSuspend1) {
278     tmp |= IADC_CTRL_ADCCLKSUSPEND1;
279   }
280   if (init->debugHalt) {
281     tmp |= IADC_CTRL_DBGHALT;
282   }
283   iadc->CTRL = tmp;
284 
285   iadc->TIMER = ((uint32_t) (init->timerCycles) << _IADC_TIMER_TIMER_SHIFT)
286                 & _IADC_TIMER_TIMER_MASK;
287 
288   iadc->CMPTHR = (((uint32_t) (init->greaterThanEqualThres) << _IADC_CMPTHR_ADGT_SHIFT)
289                   & _IADC_CMPTHR_ADGT_MASK)
290                  | (((uint32_t) (init->lessThanEqualThres) << _IADC_CMPTHR_ADLT_SHIFT)
291                     & _IADC_CMPTHR_ADLT_MASK);
292 
293   // Write configurations
294   for (config = 0; config < IADC_CONFIGNUM(IADC_NUM(iadc)); config++) {
295     // Find min allowed ADC_CLK prescaler setting for given mode
296     adcMode = allConfigs->configs[config].adcMode;
297     wantedPrescale = allConfigs->configs[config].adcClkPrescale;
298     adcClkPrescale = IADC_calcAdcClkPrescale(iadc,
299                                              IADC_ANA_CLK_MAX_FREQ(adcMode),
300                                              0,
301                                              adcMode,
302                                              srcClkPrescale);
303 
304     // Use wanted ADC_CLK prescaler setting instead if it is high enough
305     adcClkPrescale = SL_MAX(adcClkPrescale, wantedPrescale);
306 
307     tmp = iadc->CFG[config].CFG & ~(_IADC_CFG_ADCMODE_MASK | _IADC_CFG_OSRHS_MASK
308                                     | _IADC_CFG_ANALOGGAIN_MASK | _IADC_CFG_REFSEL_MASK
309 #if defined(_IADC_CFG_DIGAVG_MASK)
310                                     | _IADC_CFG_DIGAVG_MASK
311 #endif
312                                     | _IADC_CFG_TWOSCOMPL_MASK
313 #if defined(_IADC_CFG_ADCMODE_HIGHACCURACY)
314                                     | _IADC_CFG_OSRHA_MASK
315 #endif
316                                     );
317     iadc->CFG[config].CFG = tmp
318                             | (((uint32_t)(adcMode) << _IADC_CFG_ADCMODE_SHIFT) & _IADC_CFG_ADCMODE_MASK)
319                             | (((uint32_t)(allConfigs->configs[config].osrHighSpeed) << _IADC_CFG_OSRHS_SHIFT)
320                                & _IADC_CFG_OSRHS_MASK)
321 #if defined(_IADC_CFG_ADCMODE_HIGHACCURACY)
322                             | (((uint32_t)(allConfigs->configs[config].osrHighAccuracy) << _IADC_CFG_OSRHA_SHIFT)
323                                & _IADC_CFG_OSRHA_MASK)
324 #endif
325                             | (((uint32_t)(allConfigs->configs[config].analogGain) << _IADC_CFG_ANALOGGAIN_SHIFT)
326                                & _IADC_CFG_ANALOGGAIN_MASK)
327                             | (((uint32_t)(allConfigs->configs[config].reference) << _IADC_CFG_REFSEL_SHIFT)
328                                & _IADC_CFG_REFSEL_MASK)
329 #if defined(_IADC_CFG_DIGAVG_MASK)
330                             | (((uint32_t)(allConfigs->configs[config].digAvg) << _IADC_CFG_DIGAVG_SHIFT)
331                                & _IADC_CFG_DIGAVG_MASK)
332 #endif
333                             | (((uint32_t)(allConfigs->configs[config].twosComplement) << _IADC_CFG_TWOSCOMPL_SHIFT)
334                                & _IADC_CFG_TWOSCOMPL_MASK);
335 
336     uiAnaGain = (iadc->CFG[config].CFG & _IADC_CFG_ANALOGGAIN_MASK) >> _IADC_CFG_ANALOGGAIN_SHIFT;
337     switch (uiAnaGain) {
338 #if defined(_IADC_CFG_ANALOGGAIN_ANAGAIN0P25)
339       case iadcCfgAnalogGain0P25x: // 0.25x
340 #endif
341       case iadcCfgAnalogGain0P5x: // 0.5x
342       case iadcCfgAnalogGain1x: // 1x
343         uiGainCAna = (uint16_t)((DEVINFO->IADC0GAIN0 & _DEVINFO_IADC0GAIN0_GAINCANA1_MASK) >> _DEVINFO_IADC0GAIN0_GAINCANA1_SHIFT);
344         break;
345       case iadcCfgAnalogGain2x: // 2x
346         uiGainCAna = (uint16_t)((DEVINFO->IADC0GAIN0 & _DEVINFO_IADC0GAIN0_GAINCANA2_MASK) >> _DEVINFO_IADC0GAIN0_GAINCANA2_SHIFT);
347         break;
348       case iadcCfgAnalogGain3x: // 3x
349         uiGainCAna = (uint16_t)((DEVINFO->IADC0GAIN1 & _DEVINFO_IADC0GAIN1_GAINCANA3_MASK) >> _DEVINFO_IADC0GAIN1_GAINCANA3_SHIFT);
350         break;
351       case iadcCfgAnalogGain4x: // 4x
352         uiGainCAna = (uint16_t)((DEVINFO->IADC0GAIN1 & _DEVINFO_IADC0GAIN1_GAINCANA4_MASK) >> _DEVINFO_IADC0GAIN1_GAINCANA4_SHIFT);
353         break;
354       default: // 1x
355         uiGainCAna = (uint16_t)((DEVINFO->IADC0GAIN0 & _DEVINFO_IADC0GAIN0_GAINCANA1_MASK) >> _DEVINFO_IADC0GAIN0_GAINCANA1_SHIFT);
356         break;
357     }
358 
359     // Gain and offset correction is applied according to adcMode and oversampling rate.
360     switch (adcMode) {
361       float offset;
362       uint32_t scale;
363       int iOffset, iOsr;
364       case iadcCfgModeNormal:
365 #if defined(_IADC_CFG_ADCMODE_HIGHSPEED)
366       case iadcCfgModeHighSpeed:
367 #endif
368         offset = 0.0f;
369         if (uiAnaGain == iadcCfgAnalogGain2x) {
370           if (adcMode == iadcCfgModeNormal) {
371             offset = (int16_t)(DEVINFO->IADC0NORMALOFFSETCAL0 >> _DEVINFO_IADC0NORMALOFFSETCAL0_OFFSETANA2NORM_SHIFT);
372           } else {
373             offset = (int16_t)(DEVINFO->IADC0HISPDOFFSETCAL0 >> _DEVINFO_IADC0HISPDOFFSETCAL0_OFFSETANA2HISPD_SHIFT);
374           }
375         } else if (uiAnaGain == iadcCfgAnalogGain3x) {
376           if (adcMode == iadcCfgModeNormal) {
377             offset = (int16_t)(DEVINFO->IADC0NORMALOFFSETCAL0 >> _DEVINFO_IADC0NORMALOFFSETCAL0_OFFSETANA2NORM_SHIFT) * 2;
378           } else {
379             offset = (int16_t)(DEVINFO->IADC0HISPDOFFSETCAL0 >> _DEVINFO_IADC0HISPDOFFSETCAL0_OFFSETANA2HISPD_SHIFT) * 2;
380           }
381         } else if (uiAnaGain == iadcCfgAnalogGain4x) {
382           if (adcMode == iadcCfgModeNormal) {
383             offset = (int16_t)(DEVINFO->IADC0NORMALOFFSETCAL0 >> _DEVINFO_IADC0NORMALOFFSETCAL0_OFFSETANA2NORM_SHIFT) * 3;
384           } else {
385             offset = (int16_t)(DEVINFO->IADC0HISPDOFFSETCAL0 >> _DEVINFO_IADC0HISPDOFFSETCAL0_OFFSETANA2HISPD_SHIFT) * 3;
386           }
387         }
388 
389         // Set correct gain correction bitfields in scale variable.
390         tmp = (uint32_t)uiGainCAna & 0x9FFFU;
391         scale = tmp << _IADC_SCALE_GAIN13LSB_SHIFT;
392         if ((tmp & 0x8000U) != 0U) {
393           scale |= IADC_SCALE_GAIN3MSB;
394         }
395 
396         // Adjust offset according to selected OSR.
397         iOsr = 1U << (((iadc->CFG[config].CFG & _IADC_CFG_OSRHS_MASK) >> _IADC_CFG_OSRHS_SHIFT) + 1U);
398         if (iOsr == 2) {
399           if (adcMode == iadcCfgModeNormal) {
400             offset += (int16_t)(DEVINFO->IADC0NORMALOFFSETCAL0 & _DEVINFO_IADC0NORMALOFFSETCAL0_OFFSETANA1NORM_MASK);
401           } else {
402             offset += (int16_t)(DEVINFO->IADC0HISPDOFFSETCAL0 & _DEVINFO_IADC0HISPDOFFSETCAL0_OFFSETANA1HISPD_MASK);
403           }
404         } else {
405           if (adcMode == iadcCfgModeNormal) {
406             offset = (int16_t)(DEVINFO->IADC0NORMALOFFSETCAL1 & _DEVINFO_IADC0NORMALOFFSETCAL1_OFFSETANA3NORM_MASK) - offset;
407           } else {
408             offset += (int16_t)(DEVINFO->IADC0HISPDOFFSETCAL1 & _DEVINFO_IADC0HISPDOFFSETCAL1_OFFSETANA3HISPD_MASK) - offset;
409           }
410           offset /= iOsr / 2.0f;
411           offset += (int16_t)(DEVINFO->IADC0OFFSETCAL0 & _DEVINFO_IADC0OFFSETCAL0_OFFSETANABASE_MASK);
412         }
413 
414         // Compensate offset according to selected reference voltage.
415         if (allConfigs->configs[config].reference == iadcCfgReferenceInt1V2) {
416           // Internal reference voltage (VBGR) depends on the chip revision.
417           offset *= 1.25f / (IADC_getReferenceVoltage(allConfigs->configs[config].reference) / 1000.0f);
418         } else {
419           offset *= 1.25f / (allConfigs->configs[config].vRef / 1000.0f);
420         }
421 
422         // Compensate offset for systematic offset.
423         offset = (offset * 4.0f) + (640.0f * (256.0f / iOsr));
424 
425         // Apply gain error correction.
426         if (scale != 0x80000000U) {
427           offset = (uiGainCAna / 32768.0f) * (offset + 524288.0f) - 524288.0f;
428         }
429 
430         iOffset = IADC_ROUND_D2I(-offset);
431         // We only have 18 bits available for OFFSET in SCALE register.
432         // OFFSET is a 2nd complement number.
433         if (iOffset > 131071) {         // Positive overflow at 0x0001FFFF ?
434           scale |= 0x1FFFFU;
435         } else if (iOffset < -131072) { // Negative overflow at 0xFFFE0000 ?
436           scale |= 0x20000U;
437         } else {
438           scale |= (uint32_t)iOffset & 0x3FFFFU;
439         }
440         iadc->CFG[config].SCALE = scale;
441         break;
442 
443 #if defined(_IADC_CFG_ADCMODE_HIGHACCURACY)
444       case iadcCfgModeHighAccuracy:
445         // Get reference voltage in volts
446         refVoltage = IADC_getReferenceVoltage(allConfigs->configs[config].reference) / 1000.0f;
447 
448         // Get OSR from config register
449         osrValue = (iadc->CFG[config].CFG & _IADC_CFG_OSRHA_MASK) >> _IADC_CFG_OSRHA_SHIFT;
450 
451         // 1. Calculate gain correction
452         if ((uint32_t)osrHiAcc[osrValue] == 92U) {
453           // for OSR = 92, gainSysHiAcc = 0.957457
454           gainSysHiAcc = 0.957457;
455         } else {
456           // for OSR != 92, gainSysHiAcc = OSR/(OSR + 1)
457           gainSysHiAcc = osrHiAcc[osrValue] / (osrHiAcc[osrValue] + 1.0f);
458         }
459         anaGain = (float) uiGainCAna / 32768.0f * gainSysHiAcc;
460         anaGainRound =  IADC_ROUND_D2I(32768.0f * anaGain);
461         IADC0->CFG[config].SCALE &= ~_IADC_SCALE_MASK;
462 
463         // Write GAIN3MSB
464         if ((uint32_t)anaGainRound & 0x8000) {
465           IADC0->CFG[config].SCALE |= IADC_SCALE_GAIN3MSB_GAIN100;
466         } else {
467           IADC0->CFG[config].SCALE |= IADC_SCALE_GAIN3MSB_GAIN011;
468         }
469         // Write GAIN13LSB
470         IADC0->CFG[config].SCALE |= ((uint32_t)anaGainRound & 0x1FFF) << _IADC_SCALE_GAIN13LSB_SHIFT;
471 
472         // Get offset value for high accuracy mode from DEVINFO
473         offsetAna1HiAccInt = (uint16_t)(DEVINFO->IADC0OFFSETCAL0 & _DEVINFO_IADC0OFFSETCAL0_OFFSETANA1HIACC_MASK)
474                              >> _DEVINFO_IADC0OFFSETCAL0_OFFSETANA1HIACC_SHIFT;
475 
476         // 2. OSR adjustment
477         // Get offset from DEVINFO
478         offsetAnaBase = (int16_t)(DEVINFO->IADC0OFFSETCAL0 & _DEVINFO_IADC0OFFSETCAL0_OFFSETANABASE_MASK)
479                         >> _DEVINFO_IADC0OFFSETCAL0_OFFSETANABASE_SHIFT;
480         // 1 << osrValue is the same as pow(2, osrValue)
481         offsetAna = offsetAnaBase + (offsetAna1HiAccInt) / (1 << osrValue);
482 
483         // 3. Reference voltage adjustment
484         offsetAna = (offsetAna) * (1.25f / refVoltage);
485 
486         // 4. Calculate final offset
487         offset2 = 262144.0f / osrHiAcc[osrValue] / (osrHiAcc[osrValue] + 1.0f) + offsetAna * 4.0f + 524288.0f;
488         offset2 = (uiGainCAna / 32768.0f * (-1.0f)) * offset2 + 524288.0f;
489         offsetLong = IADC_ROUND_D2I(offset2);
490 
491         // 5. Write offset to scale register
492         IADC0->CFG[config].SCALE |= (uint32_t)(offsetLong & _IADC_SCALE_OFFSET_MASK);
493         break;
494 #endif
495       default:
496         // Mode not supported.
497         EFM_ASSERT(false);
498         break;
499     }
500     iadc->CFG[config].SCHED = ((adcClkPrescale << _IADC_SCHED_PRESCALE_SHIFT)
501                                & _IADC_SCHED_PRESCALE_MASK);
502   }
503   IADC_enable(iadc);
504 }
505 
506 /***************************************************************************//**
507  * @brief
508  *   Initialize IADC scan sequence.
509  *
510  * @details
511  *   This function will configure scan mode and set up entries in the scan
512  *   table. The scan table mask can be updated by calling IADC_updateScanMask.
513  *
514  * @note
515  *   This function will stop any ongoing conversions.
516  *
517  * @note If an even numbered pin is selected for the positive input, the
518  *   negative input must use an odd numbered pin and vice versa.
519  *
520  * @param[in] iadc
521  *   Pointer to IADC peripheral register block.
522  *
523  * @param[in] init
524  *   Pointer to IADC initialization structure.
525  *
526  * @param[in] scanTable
527  *   Pointer to IADC scan table structure.
528  ******************************************************************************/
IADC_initScan(IADC_TypeDef * iadc,const IADC_InitScan_t * init,const IADC_ScanTable_t * scanTable)529 void IADC_initScan(IADC_TypeDef *iadc,
530                    const IADC_InitScan_t *init,
531                    const IADC_ScanTable_t *scanTable)
532 {
533   uint32_t i;
534   uint32_t tmp;
535   EFM_ASSERT(IADC_REF_VALID(iadc));
536 #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_3)
537   // Errata IADC_E305. Makes sure that DVL is equal or less than 7 entries.
538   EFM_ASSERT(init->dataValidLevel <= iadcFifoCfgDvl7);
539 #endif
540 
541   IADC_disable(iadc);
542 
543   iadc->SCANFIFOCFG = (((uint32_t) (init->alignment) << _IADC_SCANFIFOCFG_ALIGNMENT_SHIFT)
544                        & _IADC_SCANFIFOCFG_ALIGNMENT_MASK)
545                       | (init->showId ? IADC_SCANFIFOCFG_SHOWID : 0UL)
546                       | (((uint32_t) (init->dataValidLevel) << _IADC_SCANFIFOCFG_DVL_SHIFT)
547                          & _IADC_SCANFIFOCFG_DVL_MASK)
548                       | (init->fifoDmaWakeup ? IADC_SCANFIFOCFG_DMAWUFIFOSCAN : 0UL);
549 
550   // Clear bitfields for scan conversion in IADCn->TRIGGER and set new values
551   iadc->TRIGGER = (iadc->TRIGGER & ~(_IADC_TRIGGER_SCANTRIGSEL_MASK
552                                      | _IADC_TRIGGER_SCANTRIGACTION_MASK))
553                   | (((uint32_t) (init->triggerSelect) << _IADC_TRIGGER_SCANTRIGSEL_SHIFT)
554                      & _IADC_TRIGGER_SCANTRIGSEL_MASK)
555                   | (((uint32_t) (init->triggerAction) << _IADC_TRIGGER_SCANTRIGACTION_SHIFT)
556                      & _IADC_TRIGGER_SCANTRIGACTION_MASK);
557 
558   // Write scan table
559   for (i = 0; i < IADC_SCANENTRIES(iadc); i++) {
560     iadc->SCANTABLE[i].SCAN = (((uint32_t) (scanTable->entries[i].negInput) << _IADC_SCAN_PINNEG_SHIFT)
561                                & (_IADC_SCAN_PORTNEG_MASK | _IADC_SCAN_PINNEG_MASK))
562                               | (((uint32_t) (scanTable->entries[i].posInput) << _IADC_SCAN_PINPOS_SHIFT)
563                                  & (_IADC_SCAN_PORTPOS_MASK | _IADC_SCAN_PINPOS_MASK))
564                               | (((uint32_t) (scanTable->entries[i].configId) << _IADC_SCAN_CFG_SHIFT)
565                                  & _IADC_SCAN_CFG_MASK)
566                               | (scanTable->entries[i].compare ? IADC_SCAN_CMP : 0UL);
567   }
568 
569   IADC_enable(iadc);
570 
571   // Set scan mask
572   tmp = 0;
573   for (i = 0; i < IADC_SCANENTRIES(iadc); i++) {
574     if (scanTable->entries[i].includeInScan) {
575       tmp |= (1UL << i) << _IADC_MASKREQ_MASKREQ_SHIFT;
576     }
577   }
578   iadc->MASKREQ = tmp;
579 
580   if (init->start) {
581     IADC_command(iadc, iadcCmdStartScan);
582   }
583 }
584 
585 /***************************************************************************//**
586  * @brief
587  *   Initialize single IADC conversion.
588  *
589  * @details
590  *   This function will initialize the single conversion and configure the
591  *   single input selection.
592  *
593  * @note
594  *   This function will stop any ongoing conversions.
595  *
596  * @note If an even numbered pin is selected for the positive input, the
597  *   negative input must use an odd numbered pin and vice versa.
598  *
599  * @param[in] iadc
600  *   Pointer to IADC peripheral register block.
601  *
602  * @param[in] init
603  *   Pointer to IADC single initialization structure.
604  *
605  * @param[in] input
606  *   Pointer to IADC single input selection initialization structure.
607  ******************************************************************************/
IADC_initSingle(IADC_TypeDef * iadc,const IADC_InitSingle_t * init,const IADC_SingleInput_t * input)608 void IADC_initSingle(IADC_TypeDef *iadc,
609                      const IADC_InitSingle_t *init,
610                      const IADC_SingleInput_t *input)
611 {
612   EFM_ASSERT(IADC_REF_VALID(iadc));
613 #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_3)
614   // Errata IADC_E305. Makes sure that DVL is equal or less than 7 entries.
615   EFM_ASSERT(init->dataValidLevel <= iadcFifoCfgDvl7);
616 #endif
617   IADC_disable(iadc);
618 
619   iadc->SINGLEFIFOCFG = (((uint32_t) (init->alignment) << _IADC_SINGLEFIFOCFG_ALIGNMENT_SHIFT)
620                          & _IADC_SINGLEFIFOCFG_ALIGNMENT_MASK)
621                         | (init->showId ? IADC_SINGLEFIFOCFG_SHOWID : 0UL)
622                         | (((uint32_t) (init->dataValidLevel) << _IADC_SINGLEFIFOCFG_DVL_SHIFT)
623                            & _IADC_SINGLEFIFOCFG_DVL_MASK)
624                         | (init->fifoDmaWakeup ? IADC_SINGLEFIFOCFG_DMAWUFIFOSINGLE : 0UL);
625 
626   // Clear bitfields for single conversion in IADCn->TRIGGER and set new values
627   iadc->TRIGGER = (iadc->TRIGGER & ~(_IADC_TRIGGER_SINGLETRIGSEL_MASK
628                                      | _IADC_TRIGGER_SINGLETRIGACTION_MASK
629                                      | _IADC_TRIGGER_SINGLETAILGATE_MASK))
630                   | (((uint32_t) (init->triggerSelect) << _IADC_TRIGGER_SINGLETRIGSEL_SHIFT)
631                      & _IADC_TRIGGER_SINGLETRIGSEL_MASK)
632                   | (((uint32_t) (init->triggerAction) << _IADC_TRIGGER_SINGLETRIGACTION_SHIFT)
633                      & _IADC_TRIGGER_SINGLETRIGACTION_MASK)
634                   | (init->singleTailgate ? IADC_TRIGGER_SINGLETAILGATE : 0UL);
635 
636   IADC_updateSingleInput(iadc, input);
637 
638   IADC_enable(iadc);
639 
640   if (init->start) {
641     IADC_command(iadc, iadcCmdStartSingle);
642   }
643 }
644 
645 /***************************************************************************//**
646  * @brief
647  *   Update IADC single input selection.
648  *
649  * @details
650  *   This function updates the single input selection. The function can be
651  *   called while single and/or scan conversions are ongoing and the new input
652  *   configuration will take place on the next single conversion.
653  *
654  * @note If an even numbered pin is selected for the positive input, the
655  *   negative input must use an odd numbered pin and vice versa.
656  *
657  * @param[in] iadc
658  *   Pointer to IADC peripheral register block.
659  *
660  * @param[in] input
661  *   Pointer to single input selection structure.
662  ******************************************************************************/
IADC_updateSingleInput(IADC_TypeDef * iadc,const IADC_SingleInput_t * input)663 void IADC_updateSingleInput(IADC_TypeDef *iadc,
664                             const IADC_SingleInput_t *input)
665 {
666   bool enabled;
667 
668   EFM_ASSERT(IADC_REF_VALID(iadc));
669 
670   enabled = (iadc->EN & IADC_EN_EN) != 0UL;
671 
672   // IADCn->SINGLE has WSYNC type and can only be written while enabled
673   IADC_enable(iadc);
674 
675   iadc->SINGLE = (((uint32_t) (input->negInput) << _IADC_SINGLE_PINNEG_SHIFT)
676                   & (_IADC_SINGLE_PORTNEG_MASK | _IADC_SINGLE_PINNEG_MASK))
677                  | (((uint32_t) (input->posInput) << _IADC_SINGLE_PINPOS_SHIFT)
678                     & (_IADC_SINGLE_PORTPOS_MASK | _IADC_SINGLE_PINPOS_MASK))
679                  | (((uint32_t) (input->configId) << _IADC_SINGLE_CFG_SHIFT)
680                     & _IADC_SINGLE_CFG_MASK)
681                  | (input->compare ? IADC_SINGLE_CMP : 0UL);
682 
683   // Restore enabled state
684   if (!enabled) {
685     IADC_disable(iadc);
686   }
687 }
688 
689 /***************************************************************************//**
690  * @brief
691  *   Set mask of IADC scan table entries to include in scan.
692  *
693  * @details
694  *   Set mask of scan table entries to include in next scan. This function
695  *   can be called while scan conversions are ongoing, but the new scan mask
696  *   will take effect once the ongoing scan is completed.
697  *
698  * @param[in] iadc
699  *   Pointer to IADC peripheral register block.
700  *
701  * @param[in] mask
702  *   Mask of scan table entries to include in scan.
703  ******************************************************************************/
IADC_setScanMask(IADC_TypeDef * iadc,uint32_t mask)704 void IADC_setScanMask(IADC_TypeDef *iadc, uint32_t mask)
705 {
706   bool enabled;
707 
708   EFM_ASSERT(IADC_REF_VALID(iadc));
709 
710   EFM_ASSERT(mask <= ((1UL << IADC_SCANENTRIES(iadc)) - 1UL));
711 
712   enabled = (iadc->EN & IADC_EN_EN) != 0UL;
713 
714   // IADC must be enabled to update scan table mask
715   IADC_enable(iadc);
716 
717   iadc->MASKREQ = (mask << _IADC_MASKREQ_MASKREQ_SHIFT)
718                   & _IADC_MASKREQ_MASKREQ_MASK;
719 
720   // Restore enabled state
721   if (!enabled) {
722     IADC_disable(iadc);
723   }
724 }
725 
726 /***************************************************************************//**
727  * @brief
728  *   Add/update entry in scan table.
729  *
730  * @details
731  *   This function will update or add an entry in the scan table with a specific
732  *   ID.
733  *
734  * @note
735  *   This function will stop any ongoing conversions.
736  *
737  * @param[in] iadc
738  *   Pointer to IADC peripheral register block.
739  *
740  * @param[in] id
741  *   ID of scan table entry to add.
742  *
743  * @param[in] entry
744  *   Pointer to scan table entry structure.
745  ******************************************************************************/
IADC_updateScanEntry(IADC_TypeDef * iadc,uint8_t id,IADC_ScanTableEntry_t * entry)746 void IADC_updateScanEntry(IADC_TypeDef *iadc,
747                           uint8_t id,
748                           IADC_ScanTableEntry_t *entry)
749 {
750   bool enabled;
751 
752   EFM_ASSERT(IADC_REF_VALID(iadc));
753 
754   enabled = (iadc->EN & IADC_EN_EN) != 0UL;
755 
756   // IADC must be disabled to update scan table
757   IADC_disable(iadc);
758 
759   // Update entry in scan table
760   iadc->SCANTABLE[id].SCAN = (((uint32_t) (entry->negInput) << _IADC_SCAN_PINNEG_SHIFT)
761                               & (_IADC_SCAN_PORTNEG_MASK | _IADC_SCAN_PINNEG_MASK))
762                              | (((uint32_t) (entry->posInput) << _IADC_SCAN_PINPOS_SHIFT)
763                                 & (_IADC_SCAN_PORTPOS_MASK | _IADC_SCAN_PINPOS_MASK))
764                              | (((uint32_t) (entry->configId) << _IADC_SCAN_CFG_SHIFT)
765                                 & _IADC_SCAN_CFG_MASK)
766                              | (entry->compare ? IADC_SCAN_CMP : 0UL);
767 
768   // IADC must be enabled to update scan table mask
769   IADC_enable(iadc);
770 
771   if (entry->includeInScan) {
772     iadc->MASKREQ_SET = (1UL << (id & 0x1FUL)) << _IADC_MASKREQ_MASKREQ_SHIFT;
773   } else {
774     iadc->MASKREQ_CLR = (1UL << (id & 0x1FUL)) << _IADC_MASKREQ_MASKREQ_SHIFT;
775   }
776 
777   // Restore enabled state
778   if (!enabled) {
779     IADC_disable(iadc);
780   }
781 }
782 
783 /***************************************************************************//**
784  * @brief
785  *   Reset IADC to same state as after a HW reset.
786  *
787  * @param[in] iadc
788  *   Pointer to IADC peripheral register block.
789  ******************************************************************************/
IADC_reset(IADC_TypeDef * iadc)790 void IADC_reset(IADC_TypeDef *iadc)
791 {
792   uint32_t i;
793   EFM_ASSERT(IADC_REF_VALID(iadc));
794 
795   // Write all WSYNC registers to reset value while enabled
796   IADC_enable(iadc);
797 
798   // Stop conversions and timer, before resetting other registers.
799   iadc->CMD = IADC_CMD_SINGLESTOP | IADC_CMD_SCANSTOP | IADC_CMD_TIMERDIS;
800 
801   // Wait for all IADC operations to stop
802   while ((iadc->STATUS & (IADC_STATUS_CONVERTING
803                           | IADC_STATUS_SCANQUEUEPENDING
804                           | IADC_STATUS_SINGLEQUEUEPENDING
805                           | IADC_STATUS_TIMERACTIVE))
806          != 0UL) {
807   }
808 
809   // Reset all WSYNC registers
810   iadc->MASKREQ = _IADC_MASKREQ_RESETVALUE;
811   iadc->SINGLE  = _IADC_SINGLE_RESETVALUE;
812 
813   // Wait for SINGLE and MASQREQ writes to propagate to working registers
814   while ((iadc->STATUS & (IADC_STATUS_MASKREQWRITEPENDING
815                           | IADC_STATUS_SINGLEWRITEPENDING))
816          != 0UL) {
817   }
818 
819   // Pull from FIFOs until they are empty
820 
821   // Errata IADC_E305: Check SINGLEFIFOSTAT to make sure that SINGLEFIFO is getting emptied in case
822   // where STATUS register is incorrect.
823   while (((iadc->STATUS & IADC_STATUS_SINGLEFIFODV) != 0UL) || (iadc->SINGLEFIFOSTAT > 0)) {
824     (void) IADC_pullSingleFifoData(iadc);
825   }
826 
827   // Errata IADC_E305: check SCANFIFOSTAT to make sure that SCANFIFO is getting emptied in case
828   // where STATUS register is incorrect.
829   while (((iadc->STATUS & IADC_STATUS_SCANFIFODV) != 0UL) || (iadc->SCANFIFOSTAT > 0)) {
830     (void) IADC_pullScanFifoData(iadc);
831   }
832 
833   // Read data registers to clear data valid flags
834   (void) IADC_readSingleData(iadc);
835   (void) IADC_readScanData(iadc);
836 
837   // Write all WSTATIC registers to reset value while disabled
838   IADC_disable(iadc);
839 
840   // Reset all WSTATIC registers
841   iadc->CTRL            = _IADC_CTRL_RESETVALUE;
842   iadc->TIMER           = _IADC_TIMER_RESETVALUE;
843   iadc->TRIGGER         = _IADC_TRIGGER_RESETVALUE;
844 
845   iadc->CMPTHR          = _IADC_CMPTHR_RESETVALUE;
846   iadc->SINGLEFIFOCFG   = _IADC_SINGLEFIFOCFG_RESETVALUE;
847   iadc->SCANFIFOCFG     = _IADC_SCANFIFOCFG_RESETVALUE;
848 
849   for (i = 0; i < IADC_CONFIGNUM(IADC_NUM(iadc)); i++) {
850     iadc->CFG[i].CFG    = _IADC_CFG_RESETVALUE;
851     iadc->CFG[i].SCALE  = _IADC_SCALE_RESETVALUE;
852     iadc->CFG[i].SCHED  = _IADC_SCHED_RESETVALUE;
853   }
854 
855   for (i = 0; i < IADC_SCANENTRIES(iadc); i++) {
856     iadc->SCANTABLE[i].SCAN = _IADC_SCAN_RESETVALUE;
857   }
858 
859   // Clear interrupt flags and disable interrupts
860   IADC_clearInt(iadc, _IADC_IF_MASK);
861   IADC_disableInt(iadc, _IADC_IEN_MASK);
862 }
863 
864 /***************************************************************************//**
865  * @brief
866  *   Calculate timebase value in order to get a timebase providing at least 1us.
867  *
868  * @param[in] iadc
869  *   Pointer to IADC peripheral register block.
870  *
871  * @param[in] srcClkFreq Frequency in Hz of reference CLK_SRC_ADC clock. Set to 0 to
872  *   derive srcClkFreq from CLK_CMU_ADC and prescaler HSCLKRATE.
873  *
874  * @return
875  *   Timebase value to use for IADC in order to achieve at least 1 us.
876  ******************************************************************************/
IADC_calcTimebase(IADC_TypeDef * iadc,uint32_t srcClkFreq)877 uint8_t IADC_calcTimebase(IADC_TypeDef *iadc, uint32_t srcClkFreq)
878 {
879   EFM_ASSERT(IADC_REF_VALID(iadc));
880 
881   if (srcClkFreq == 0UL) {
882     // CLK_SRC_ADC is derived from CLK_CMU_ADC, and must be no faster than 40 MHz. Therefore we set
883     // srcClkFreq's original value to CLK_CMU_ADC before evaluating the prescaling conditions.
884     srcClkFreq = CMU_ClockFreqGet(cmuClock_IADC0);
885 
886     // Just in case, make sure we get non-zero frequency for below calculation
887     if (srcClkFreq == 0UL) {
888       srcClkFreq = 1;
889     }
890     // If srcClkFreq is greater than 40MHz, then divide by the prescaler HSCLKRATE
891     if (srcClkFreq > IADC_CLK_MAX_FREQ) {
892       uint32_t prescaler = (uint32_t)(IADC0->CTRL & _IADC_CTRL_HSCLKRATE_MASK) >> _IADC_CTRL_HSCLKRATE_SHIFT;
893       srcClkFreq /= (prescaler + 1);
894     }
895   }
896 
897   // Determine number of ADCCLK cycle >= 1us
898   srcClkFreq += 999999UL;
899   srcClkFreq /= 1000000UL;
900 
901   // Convert to N+1 format
902   srcClkFreq -= 1UL;
903 
904   // Limit to max allowed register setting
905   srcClkFreq = SL_MIN(srcClkFreq, (_IADC_CTRL_TIMEBASE_MASK >> _IADC_CTRL_TIMEBASE_SHIFT));
906 
907   // Return timebase value
908   return (uint8_t) srcClkFreq;
909 }
910 
911 /***************************************************************************//**
912  * @brief
913  *   Calculate prescaler for CLK_SRC_ADC high speed clock
914  *
915  * @details
916  *   The IADC high speed clock is given by: CLK_SRC_ADC / (srcClkPrescaler + 1).
917  *
918  * @param[in] iadc
919  *   Pointer to IADC peripheral register block.
920  *
921  * @param[in] srcClkFreq CLK_SRC_ADC frequency wanted. The frequency will
922  *   automatically be adjusted to be within valid range according to reference
923  *   manual.
924  *
925  * @param[in] cmuClkFreq Frequency in Hz of reference CLK_CMU_ADC. Set to 0
926  *   to use currently defined CMU clock setting for the IADC.
927  *
928  * @return
929  *   Divider value to use for IADC in order to achieve a high speed clock value
930  *   <= @p srcClkFreq.
931  ******************************************************************************/
IADC_calcSrcClkPrescale(IADC_TypeDef * iadc,uint32_t srcClkFreq,uint32_t cmuClkFreq)932 uint8_t IADC_calcSrcClkPrescale(IADC_TypeDef *iadc,
933                                 uint32_t srcClkFreq,
934                                 uint32_t cmuClkFreq)
935 {
936   uint32_t ret;
937 
938   EFM_ASSERT(IADC_REF_VALID(iadc));
939   EFM_ASSERT(srcClkFreq);
940 
941   // Make sure wanted CLK_SRC_ADC clock is below max allowed frequency
942   srcClkFreq = SL_MIN(srcClkFreq, IADC_CLK_MAX_FREQ);
943 
944   // Use current CLK_CMU_ADC frequency?
945   if (cmuClkFreq == 0UL) {
946     cmuClkFreq = CMU_ClockFreqGet(IADC_CMU_CLOCK(iadc));
947   }
948 
949   ret = (cmuClkFreq + srcClkFreq - 1UL) / srcClkFreq;
950   if (ret != 0UL) {
951     ret--;
952   }
953 
954   // Limit to max allowed register setting
955   if (ret > _IADC_CTRL_HSCLKRATE_DIV4) {
956     ret = _IADC_CTRL_HSCLKRATE_DIV4;
957   }
958 
959   return (uint8_t)ret;
960 }
961 
962 /***************************************************************************//**
963  * @brief
964  *   Calculate prescaler for ADC_CLK clock.
965  *
966  * @details
967  *   The ADC_CLK is given by: CLK_SRC_ADC / (adcClkprescale + 1).
968  *
969  * @param[in] iadc
970  *   Pointer to IADC peripheral register block.
971  *
972  * @param[in] adcClkFreq  ADC_CLK frequency wanted. The frequency will
973  *   automatically be adjusted to be within valid range according to reference
974  *   manual.
975  *
976  * @param[in] cmuClkFreq Frequency in Hz of CLK_CMU_ADC Set to 0 to
977  *   use currently defined IADC clock setting (in CMU).
978  *
979  * @param[in] adcMode Mode for IADC config.
980  *
981  * @param[in] srcClkPrescaler Precaler setting for ADC_CLK
982  *
983  * @return
984  *   Divider value to use for IADC in order to achieve a ADC_CLK frequency
985  *   <= @p adcClkFreq.
986  ******************************************************************************/
IADC_calcAdcClkPrescale(IADC_TypeDef * iadc,uint32_t adcClkFreq,uint32_t cmuClkFreq,IADC_CfgAdcMode_t adcMode,uint8_t srcClkPrescaler)987 uint32_t IADC_calcAdcClkPrescale(IADC_TypeDef *iadc,
988                                  uint32_t adcClkFreq,
989                                  uint32_t cmuClkFreq,
990                                  IADC_CfgAdcMode_t adcMode,
991                                  uint8_t srcClkPrescaler)
992 {
993   uint32_t ret;
994   uint32_t resFreq;
995 
996   EFM_ASSERT(IADC_REF_VALID(iadc));
997   EFM_ASSERT(adcClkFreq);
998 
999   // Make sure wanted analog clock is below max allowed frequency for the given
1000   // mode.
1001   if (adcClkFreq > IADC_ANA_CLK_MAX_FREQ(adcMode)) {
1002     adcClkFreq = IADC_ANA_CLK_MAX_FREQ(adcMode);
1003   }
1004 
1005   // Use current CLK_CMU_ADC frequency?
1006   if (cmuClkFreq == 0UL) {
1007     resFreq = CMU_ClockFreqGet(IADC_CMU_CLOCK(iadc));
1008   } else {
1009     resFreq = cmuClkFreq;
1010   }
1011 
1012   // Apply CLK_SRC_ADC prescaler
1013   resFreq /= srcClkPrescaler + 1UL;
1014 
1015   ret = (resFreq + adcClkFreq - 1UL) / adcClkFreq;
1016   if (ret != 0UL) {
1017     ret--;
1018   }
1019 
1020   // Limit to max allowed register setting
1021   ret = SL_MIN(ret, (_IADC_SCHED_PRESCALE_MASK >> _IADC_SCHED_PRESCALE_SHIFT));
1022 
1023   return (uint16_t)ret;
1024 }
1025 
1026 /***************************************************************************//**
1027  * @brief
1028  *   Pull result from single data FIFO. The result struct includes both the data
1029  *   and the ID (0x20) if showId was set when initializing single mode.
1030  *
1031  * @note
1032  *   Check data valid flag before calling this function.
1033  *
1034  * @param[in] iadc
1035  *   Pointer to IADC peripheral register block.
1036  *
1037  * @return
1038  *   Single conversion result struct holding data and id.
1039  ******************************************************************************/
IADC_pullSingleFifoResult(IADC_TypeDef * iadc)1040 IADC_Result_t IADC_pullSingleFifoResult(IADC_TypeDef *iadc)
1041 {
1042   uint32_t alignment = (iadc->SINGLEFIFOCFG & _IADC_SINGLEFIFOCFG_ALIGNMENT_MASK)
1043                        >> _IADC_SINGLEFIFOCFG_ALIGNMENT_SHIFT;
1044   return IADC_ConvertRawDataToResult(iadc->SINGLEFIFODATA,
1045                                      (IADC_Alignment_t) alignment);
1046 }
1047 
1048 /***************************************************************************//**
1049  * @brief
1050  *   Read most recent single conversion result. The result struct includes both
1051  *   the data and the ID (0x20) if showId was set when initializing single mode.
1052  *   Calling this function will not affect the state of the single data FIFO.
1053  *
1054  * @note
1055  *   Check data valid flag before calling this function.
1056  *
1057  * @param[in] iadc
1058  *   Pointer to IADC peripheral register block.
1059  *
1060  * @return
1061  *   Single conversion result struct holding data and id.
1062  ******************************************************************************/
IADC_readSingleResult(IADC_TypeDef * iadc)1063 IADC_Result_t IADC_readSingleResult(IADC_TypeDef *iadc)
1064 {
1065   uint32_t alignment = (iadc->SINGLEFIFOCFG & _IADC_SINGLEFIFOCFG_ALIGNMENT_MASK)
1066                        >> _IADC_SINGLEFIFOCFG_ALIGNMENT_SHIFT;
1067   return IADC_ConvertRawDataToResult(iadc->SINGLEDATA,
1068                                      (IADC_Alignment_t) alignment);
1069 }
1070 
1071 /***************************************************************************//**
1072  * @brief
1073  *   Pull result from scan data FIFO. The result struct includes both the data
1074  *   and the ID (0x20) if showId was set when initializing scan entry.
1075  *
1076  * @note
1077  *   Check data valid flag before calling this function.
1078  *
1079  * @param[in] iadc
1080  *   Pointer to IADC peripheral register block.
1081  *
1082  * @return
1083  *   Scan conversion result struct holding data and id.
1084  ******************************************************************************/
IADC_pullScanFifoResult(IADC_TypeDef * iadc)1085 IADC_Result_t IADC_pullScanFifoResult(IADC_TypeDef *iadc)
1086 {
1087   uint32_t alignment = (iadc->SCANFIFOCFG & _IADC_SCANFIFOCFG_ALIGNMENT_MASK)
1088                        >> _IADC_SCANFIFOCFG_ALIGNMENT_SHIFT;
1089   return IADC_ConvertRawDataToResult(iadc->SCANFIFODATA,
1090                                      (IADC_Alignment_t) alignment);
1091 }
1092 
1093 /***************************************************************************//**
1094  * @brief
1095  *   Read most recent scan conversion result. The result struct includes both
1096  *   the data and the ID (0x20) if showId was set when initializing scan entry.
1097  *   Calling this function will not affect the state of the scan data FIFO.
1098  *
1099  * @note
1100  *   Check data valid flag before calling this function.
1101  *
1102  * @param[in] iadc
1103  *   Pointer to IADC peripheral register block.
1104  *
1105  * @return
1106  *   Scan conversion result struct holding data and id.
1107  ******************************************************************************/
IADC_readScanResult(IADC_TypeDef * iadc)1108 IADC_Result_t IADC_readScanResult(IADC_TypeDef *iadc)
1109 {
1110   uint32_t alignment = (iadc->SCANFIFOCFG & _IADC_SCANFIFOCFG_ALIGNMENT_MASK)
1111                        >> _IADC_SCANFIFOCFG_ALIGNMENT_SHIFT;
1112   return IADC_ConvertRawDataToResult(iadc->SCANDATA,
1113                                      (IADC_Alignment_t) alignment);
1114 }
1115 
1116 /***************************************************************************//**
1117  * @brief
1118  *   Get reference voltage selection.
1119  *
1120  * @param[in] reference
1121  *   IADC Reference selection.
1122  *
1123  * @return
1124  *   IADC reference voltage in millivolts.
1125  ******************************************************************************/
IADC_getReferenceVoltage(IADC_CfgReference_t reference)1126 uint32_t IADC_getReferenceVoltage(IADC_CfgReference_t reference)
1127 {
1128   uint32_t refVoltage = 0;
1129   // Get chip revision
1130   SYSTEM_ChipRevision_TypeDef chipRev;
1131   SYSTEM_ChipRevisionGet(&chipRev);
1132   switch (reference) {
1133     case iadcCfgReferenceInt1V2:
1134 #if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1)
1135       if (chipRev.major == 1UL) {
1136         refVoltage = 1210;
1137       } else {
1138         refVoltage = 1180;
1139       }
1140 #else
1141       refVoltage = 1210;
1142 #endif
1143       break;
1144     case iadcCfgReferenceExt1V25:
1145       refVoltage = 1250;
1146       break;
1147 #if defined(_IADC_CFG_REFSEL_VREF2P5)
1148     case iadcCfgReferenceExt2V5:
1149       refVoltage = 2500;
1150       break;
1151 #endif
1152     case iadcCfgReferenceVddx:
1153       refVoltage = 3000;
1154       break;
1155     case iadcCfgReferenceVddX0P8Buf:
1156       refVoltage = 2400;
1157       break;
1158 #if defined(_IADC_CFG_REFSEL_VREFBUF)
1159     case iadcCfgReferenceBuf:
1160       refVoltage = 12500;
1161       break;
1162 #endif
1163 #if defined(_IADC_CFG_REFSEL_VREF0P8BUF)
1164     case iadcCfgReference0P8Buf:
1165       refVoltage = 1000;
1166       break;
1167 #endif
1168     default:
1169       EFM_ASSERT(false);
1170       break;
1171   }
1172 
1173   return refVoltage;
1174 }
1175 
1176 /** @} (end addtogroup iadc) */
1177 /** @} (end addtogroup emlib) */
1178 #endif /* defined(IADC_COUNT) && (IADC_COUNT > 0) */
1179