-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathADC.cpp
500 lines (434 loc) · 11.8 KB
/
ADC.cpp
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
498
499
500
#include "ADC.hpp"
adc::AdcCalData adc::calData;
static void syncgclk()
{
while (GCLK->STATUS.bit.SYNCBUSY);
}
static void syncadc()
{
while (ADC->STATUS.bit.SYNCBUSY);
}
static std::uint16_t s_sample()
{
ADC->SWTRIG.bit.START = 1; // Initiate software trigger to start ADC conversion
syncadc();
while (!ADC->INTFLAG.bit.RESRDY); // Wait for conversion
ADC->INTFLAG.bit.RESRDY = 1; // Clear interrupt flag
syncadc();
return ADC->RESULT.reg;
}
std::uint16_t adc::toCounts(std::uint16_t val, std::uint8_t resolution)
{
const auto resDelta = std::int8_t(resolution) - ADC_RESOLUTION_BITS;
if (!resDelta)
{
return val;
}
else if (resDelta < 0)
{
return (val >> (-resDelta));
}
else
{
return (val << resDelta);
}
}
std::uint16_t adc::fromCounts(std::uint16_t val, std::uint8_t resolution)
{
return adc::toCounts(val, 2 * ADC_RESOLUTION_BITS - resolution);
}
adc::LogRow::LogRow()
{
const auto regVal1 = ADC_CAL_LOG_ROW_READ(0), regVal2 = ADC_CAL_LOG_ROW_READ(1);
this->roomTempValInt = ADC_CAL_EXTRACT(regVal1, ADC_CAL_ROOM_TEMP_VAL_INT);
this->roomTempValDec = ADC_CAL_EXTRACT(regVal1, ADC_CAL_ROOM_TEMP_VAL_DEC);
this->hotTempValInt = ADC_CAL_EXTRACT(regVal1, ADC_CAL_HOT_TEMP_VAL_INT);
this->hotTempValDec = ADC_CAL_EXTRACT(regVal1, ADC_CAL_HOT_TEMP_VAL_DEC);
this->roomInt1VVal = ADC_CAL_EXTRACT(regVal1, ADC_CAL_ROOM_INT1V_VAL);
this->hotInt1VVal = ADC_CAL_EXTRACT(regVal2, ADC_CAL_HOT_INT1V_VAL);
this->roomAdcVal = ADC_CAL_EXTRACT(regVal2, ADC_CAL_ROOM_ADC_VAL);
this->hotAdcVal = ADC_CAL_EXTRACT(regVal2, ADC_CAL_HOT_ADC_VAL);
const auto calcref = [](std::int8_t val) -> float
{
return 1.0f - float(val) / 1000.f;
};
// Calculate constants
this->INT1VH = calcref(this->hotInt1VVal);
this->INT1VR = calcref(this->roomInt1VVal);
this->tempH = float(this->hotTempValInt) + float(this->hotTempValDec) / 10.0f;
this->tempR = float(this->roomTempValInt) + float(this->roomTempValDec) / 10.0f;
this->VADCH = float(this->hotAdcVal) / (this->INT1VH * this->maxCountsFloat);
this->VADCR = float(this->roomAdcVal) / (this->INT1VR * this->maxCountsFloat);
}
std::uint8_t adc::init(std::uint8_t adcResolution, std::uint16_t overSamplingSamples)
{
std::uint8_t ret = adcResolution;
// Set up ADC clock source
GCLK->GENCTRL.reg |=
GCLK_GENCTRL_ID(3) | // Use GLK3, as it is already set up as 8 MHz internal OSC
GCLK_GENCTRL_GENEN;
syncgclk();
// Set ADC to use GCLK3 as 8 Mhz
GCLK->CLKCTRL.reg =
GCLK_CLKCTRL_ID_ADC |
GCLK_CLKCTRL_GEN_GCLK3 |
GCLK_CLKCTRL_CLKEN;
syncgclk();
// Select ADC reference
analogReference(AR_INTERNAL1V0);
uint32_t bias = (*((uint32_t *) ADC_FUSES_BIASCAL_ADDR) & ADC_FUSES_BIASCAL_Msk) >> ADC_FUSES_BIASCAL_Pos;
uint32_t linearity = (*((uint32_t *) ADC_FUSES_LINEARITY_0_ADDR) & ADC_FUSES_LINEARITY_0_Msk) >> ADC_FUSES_LINEARITY_0_Pos;
linearity |= ((*((uint32_t *) ADC_FUSES_LINEARITY_1_ADDR) & ADC_FUSES_LINEARITY_1_Msk) >> ADC_FUSES_LINEARITY_1_Pos) << 5;
/* Wait for bus synchronization. */
syncadc();
/* Write the calibration data. */
ADC->CALIB.reg = ADC_CALIB_BIAS_CAL(bias) | ADC_CALIB_LINEARITY_CAL(linearity);
syncadc();
// Configure ADC resolution
std::uint32_t initialRes;
switch (adcResolution)
{
case 8:
initialRes = ADC_CTRLB_RESSEL_8BIT;
break;
case 10:
initialRes = ADC_CTRLB_RESSEL_10BIT;
break;
case 12:
case 13:
case 14:
case 15:
case 16:
initialRes = ADC_CTRLB_RESSEL_12BIT;
break;
default:
assert(!"Invalid ADC resolution!");
}
ADC->CTRLB.reg = ADC_CLK_DIV | initialRes; // Select initial ADC resolution & peripheral clock divider
syncadc();
if ((adcResolution > 12) || ((adcResolution == 12) && overSamplingSamples))
{
// Enable averaging mode
std::uint32_t sNum;
if (overSamplingSamples)
{
switch (overSamplingSamples)
{
case 1:
sNum = ADC_AVGCTRL_SAMPLENUM_1;
overSamplingSamples = 0;
break;
case 2:
sNum = ADC_AVGCTRL_SAMPLENUM_2;
overSamplingSamples = 1;
break;
case 4:
sNum = ADC_AVGCTRL_SAMPLENUM_4;
overSamplingSamples = 2;
break;
case 8:
sNum = ADC_AVGCTRL_SAMPLENUM_8;
overSamplingSamples = 3;
break;
case 16:
sNum = ADC_AVGCTRL_SAMPLENUM_16;
overSamplingSamples = 4;
break;
case 32:
sNum = ADC_AVGCTRL_SAMPLENUM_32;
overSamplingSamples = 5;
break;
case 64:
sNum = ADC_AVGCTRL_SAMPLENUM_64;
overSamplingSamples = 6;
break;
case 128:
sNum = ADC_AVGCTRL_SAMPLENUM_128;
overSamplingSamples = 7;
break;
case 256:
sNum = ADC_AVGCTRL_SAMPLENUM_256;
overSamplingSamples = 8;
break;
case 512:
sNum = ADC_AVGCTRL_SAMPLENUM_512;
overSamplingSamples = 9;
break;
case 1024:
sNum = ADC_AVGCTRL_SAMPLENUM_1024;
overSamplingSamples = 10;
break;
default:
assert(!"Invalid number of oversampling samples!");
}
}
else
{
switch (adcResolution)
{
case 12:
sNum = ADC_AVGCTRL_SAMPLENUM_2;
overSamplingSamples = 1;
break;
case 13:
sNum = ADC_AVGCTRL_SAMPLENUM_4;
overSamplingSamples = 2;
break;
case 14:
sNum = ADC_AVGCTRL_SAMPLENUM_16;
overSamplingSamples = 4;
break;
case 15:
sNum = ADC_AVGCTRL_SAMPLENUM_64;
overSamplingSamples = 6;
break;
case 16:
sNum = ADC_AVGCTRL_SAMPLENUM_256;
overSamplingSamples = 8;
break;
default:
assert(!"This error is impossible to produce!");
}
}
/*
Oversampling ADJRES config table for 12 ... 16 bits output
12 bits:
0 -> 1 sample -> 0
1 -> 2 samples -> 1
2 -> 4 samples -> 2
3 -> 8 samples -> 3
4 -> 16 samples -> 4
...
13 bits:
1 -> (2 samples)-> 0
2 -> 4 samples -> 1
3 -> 8 samples -> 2
4 -> 16 samples -> 3
5 -> 32 samples -> 3
6 -> 64 samples -> 3
...
14 bits:
2 -> (4 samples) -> 0
3 -> (8 samples) -> 1
4 -> 16 samples -> 2
5 -> 32 samples -> 2
6 -> 64 samples -> 2
7 -> 128 samples -> 2
8 -> 256 samples -> 2
...
15 bits:
5 -> (32 samples) -> 0
6 -> 64 samples -> 1
7 -> 128 samples -> 1
8 -> 256 samples -> 1
9 -> 512 samples -> 1
10 -> 1024 samples -> 1
16 bits:
8 -> 256 samples -> 0
9 -> 512 samples -> 0
10 -> 1024 samples -> 0
*/
adcResolution -= 12;
std::int8_t adjRes = adc::clamp<std::int8_t>(overSamplingSamples, 0, 4) - adcResolution;
adjRes = adc::clamp<std::int8_t>(adjRes, 0, 4);
// Calculate real achievable resolution
const auto minOverSample = 2 * adcResolution;
ret -= adc::clamp<std::int8_t>((minOverSample - overSamplingSamples) / 2, 0, 4);
adcResolution += 12;
ADC->AVGCTRL.reg = sNum | ADC_AVGCTRL_ADJRES(adjRes); // Select averaging amount
syncadc();
ADC->CTRLB.reg |= ADC_CTRLB_RESSEL_16BIT; // Activate averaging mode by selecting 16 bit resolution
syncadc();
}
// Calibrate ADC only if setting up was successful
if (ret == adcResolution)
{
adc::startAdc();
adc::setSamplingTime(63);
const auto tempSample = adc::sample(Channel::IntTemp, true);
adc::setSamplingTime(0);
adc::calibrate(tempSample, true);
adc::getSupply(true);
}
return ret;
}
void adc::startAdc()
{
// Enable ADC peripheral
PM->APBCMASK.reg |= PM_APBCMASK_ADC;
// Enable temperature sensor
SYSCTRL->VREF.bit.TSEN = 1;
// Enable ADC
ADC->CTRLA.bit.ENABLE = 0x01;
syncadc();
// The first sample is rubbish anyway
s_sample();
}
void adc::stopAdc()
{
// Disable ADC
ADC->CTRLA.bit.ENABLE = 0x00;
syncadc();
// Disable temp sensor
SYSCTRL->VREF.bit.TSEN = 0;
// Disable ADC peripheral to save power
PM->APBCMASK.reg &= ~PM_APBCMASK_ADC;
}
void adc::setGain(Gain gainIdx)
{
std::uint8_t gain;
switch (gainIdx)
{
case Gain::g0_5x:
gain = 0xF;
break;
case Gain::g1x:
gain = 0x0;
break;
case Gain::g2x:
gain = 0x1;
break;
case Gain::g4x:
gain = 0x2;
break;
case Gain::g8x:
gain = 0x3;
break;
case Gain::g16x:
gain = 0x4;
break;
default:
assert(!"Invalid gain setting!");
}
adc::calData.gainIdx = std::uint8_t(gainIdx);
adc::calData.gainSetting = gain;
}
void adc::setSamplingTime(std::uint8_t time)
{
assert(time < 64);
ADC->SAMPCTRL.reg = time;
syncadc();
}
std::uint16_t adc::sample(Channel channel, bool preciseTemp, bool diffMode)
{
preciseTemp &= (ADC_CLK_DIV != ADC_SLOW_CLK_DIV);
const auto prescaler = ADC->CTRLB.bit.PRESCALER;
if (preciseTemp)
{
ADC->CTRLB.bit.PRESCALER = ADC_SLOW_CLK_DIV >> ADC_CTRLB_PRESCALER_Pos;
syncadc();
}
if (ADC->CTRLB.bit.DIFFMODE != diffMode)
{
ADC->CTRLB.bit.DIFFMODE = diffMode;
syncadc();
}
std::uint8_t chPos, chNeg = 0x19;
switch (channel)
{
case Channel::Out:
chPos = adc::pinToMux(CAP_OUT);
break;
case Channel::OutAmp:
chPos = adc::pinToMux(ESR_OUT_11X);
break;
case Channel::IntTemp:
chPos = 0x18;
break;
case Channel::Cal0:
chPos = 0x00;
chNeg = 0x00;
break;
case Channel::CalRef:
chPos = 0x19;
break;
case Channel::IOSupply_1_4:
chPos = 0x1B;
break;
case Channel::CoreSupply_1_4:
chPos = 0x1A;
chNeg = 0x18;
break;
default:
assert(!"Invalid adc channel!");
}
ADC->INPUTCTRL.bit.MUXPOS = chPos; // Select MUX channel
syncadc();
if (diffMode)
{
ADC->INPUTCTRL.bit.MUXNEG = (channel == Channel::IntTemp) ? 0x18 : chNeg; // Select I/O ground as negative input, internal ground for temperature sensing
syncadc();
}
// Select proper gain, temperature gain must be 1x
ADC->INPUTCTRL.bit.GAIN = (channel == Channel::IntTemp) ? 0x00 : adc::calData.gainSetting;
syncadc();
if (preciseTemp)
{
s_sample();
}
const auto result = s_sample();
if (preciseTemp)
{
ADC->CTRLB.bit.PRESCALER = prescaler;
syncadc();
}
return result;
}
float adc::getVolts(std::uint16_t sample)
{
return float(fp::fromD(adc::getVolts_fpd(sample)));
}
std::uint32_t adc::getVolts_fpd(std::uint16_t sample)
{
std::uint32_t maxCounts = ADC_MAX_COUNTS << 11;
if (adc::Gain(adc::calData.gainIdx) != adc::Gain::g1x)
{
std::uint32_t gainFPD = adc::calData.gainCal_FPD[adc::calData.gainIdx];
maxCounts = fp::mul(maxCounts, gainFPD);
}
/*SerialUSB.print("Sample: ");
SerialUSB.print(sample);
SerialUSB.print("; Max counts: ");
SerialUSB.println(maxCounts >> 11);*/
std::uint32_t volts = fp::muldiv(adc::calData.ref1VReal_FPD, sample << 11, maxCounts);
return volts;
}
void adc::calibrate(std::uint16_t tempSample, bool fullCal)
{
if (fullCal)
{
// Calibrate zero
const auto oldGain = adc::calData.gainIdx;
std::uint32_t refMax = adc::sample(Channel::IOSupply_1_4, true);
adc::setGain(Gain::g0_5x);
std::uint32_t refCounts = adc::sample(Channel::IOSupply_1_4, true);
adc::calData.gainCal_FPD[std::uint8_t(Gain::g0_5x)] = fp::div(refCounts << 15U, refMax << 15U);
adc::setGain(Gain::g1x);
refMax = adc::sample(Channel::CoreSupply_1_4, true);
adc::setGain(Gain::g2x);
refCounts = adc::sample(Channel::CoreSupply_1_4, true);
adc::calData.gainCal_FPD[std::uint8_t(Gain::g2x)] = fp::div(refCounts << 15U, refMax << 15);
adc::setGain(Gain(oldGain));
}
// Slightly modified code from Atmel application note AT11481: ADC Configurations with Examples
float INT1VM; /* Voltage calculation for reality INT1V value during the ADC conversion */
const auto & lr = adc::calData.lr;
const auto coarse_temp = adc::getTemp(tempSample);
INT1VM = lr.INT1VR + (((lr.INT1VH - lr.INT1VR) * (coarse_temp - lr.tempR)) / (lr.tempH - lr.tempR));
// Set new reference calibration value
adc::calData.ref1VReal = INT1VM;
adc::calData.ref1VReal_FPD = fp::to(adc::calData.ref1VReal);
}
float adc::getTemp(std::uint16_t tempSample)
{
const auto & lr = adc::calData.lr;
const auto volts = adc::getVolts(tempSample);
return lr.tempR + ((lr.tempH - lr.tempR) * (volts - lr.VADCR)/(lr.VADCH - lr.VADCR));
}
float adc::getSupply(bool preciseMeas)
{
const auto sample = adc::sample(Channel::IOSupply_1_4, preciseMeas);
adc::calData.supplyVoltage_FPD = 4U * adc::getVolts_fpd(sample);
adc::calData.supplyVoltage = fp::fromD(adc::calData.supplyVoltage_FPD);
return adc::calData.supplyVoltage;
}