#define AMBIENT_ADC N_PWMLEDS
#define BATTERY_ADC (N_PWMLEDS + 1)
+#define ADC1_GAIN20 (N_PWMLEDS + 2)
-#define NUM_ADCS 5
+#define NUM_ADCS 6
volatile static unsigned char current_adc;
static uint16_t adc_sum;
static unsigned char sum_shift;
static unsigned char adc_vals;
+#define ADC1_GAIN20_OFFSET_SHIFT 6
+static uint16_t adc1_gain20_offset;
static void inline setup_mux(unsigned char n)
{
- ADCSRA |= _BV(ADEN); // enable ADC
-
/* ADC numbering: PWM LEDs first, then ambient light sensor, battery sensor */
switch (n) {
case 0: // pwmled 1: 1.1V, ADC0,1 (PA0,1), gain 20
ADMUX = _BV(REFS1) | _BV(MUX2) | _BV(MUX1);
sum_shift = 0; // 1 measurement
break;
+ case 5: // gain stage offset: 1.1V, ADC1,1, gain 20
+ ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
+ sum_shift = 0; // 1 measurement
+ break;
}
adc_sum = 0;
void init_adc()
{
+ unsigned char i;
current_adc = NUM_ADCS;
ADCSRA = _BV(ADEN) // enable
DIDR0 = _BV(ADC0D) | _BV(ADC1D) | _BV(ADC2D)
| _BV(ADC4D) | _BV(ADC5D) | _BV(ADC6D);
+ // 1.1V, ADC1,1, gain 20
+ ADMUX = _BV(REFS1) | _BV(MUX3) | _BV(MUX2) | _BV(MUX0);
ADCSRA |= _BV(ADSC);
/* Do first conversion and drop the result */
while ((ADCSRA & _BV(ADIF)) == 0)
;
ADCSRA |= _BV(ADIF); // clear the IRQ flag
- ADCSRA |= _BV(ADIE); // enable IRQ
- ADCSRA &= ~_BV(ADEN); // disable until needed
+ adc1_gain20_offset = 0;
+
+ for (i = 0; i < (1 << ADC1_GAIN20_OFFSET_SHIFT); i++) {
+ ADCSRA |= _BV(ADSC);
+
+ while ((ADCSRA & _BV(ADIF)) == 0)
+ ;
+ adc1_gain20_offset += ADCW
+ - (adc1_gain20_offset >> ADC1_GAIN20_OFFSET_SHIFT);
+
+ ADCSRA |= _BV(ADIF); // clear the IRQ flag
+ }
+
+ ADCSRA |= _BV(ADIE); // enable IRQ
}
void susp_adc()
if (adc_vals)
// start the next conversion immediately
ADCSRA |= _BV(ADSC);
- else
- ADCSRA &= ~_BV(ADEN); // the last one, disable ADC
if (adc_vals < (1 << sum_shift))
// drop the first conversion, use all others
adcval = adc_sum >> sum_shift;
+ if (current_adc == ADC1_GAIN20) {
+ // running average
+ adc1_gain20_offset += adcval
+ - (adc1_gain20_offset >> ADC1_GAIN20_OFFSET_SHIFT);
+ } else if (current_adc == 0 || current_adc == 1) {
+ uint16_t offset = adc1_gain20_offset
+ >> (ADC1_GAIN20_OFFSET_SHIFT - sum_shift);
+ if (adc_sum > offset)
+ adc_sum -= offset;
+ else
+ adc_sum = 0;
+ }
+
if (current_adc < N_PWMLEDS)
- pwmled_adc(current_adc, adcval);
+ pwmled_adc(current_adc, adc_sum);
if (current_adc == AMBIENT_ADC)
ambient_adc(adcval);
if (current_adc == BATTERY_ADC)
{
if (current_adc == NUM_ADCS) // Don't start if in progress
start_next_adc();
+#if 0
+ else
+ log_byte(0x99);
+#endif
}