#ifndef F_CPU #define F_CPU 16000000UL #endif #include #include #include #include #include #define DIGIT_MASK 0x0F #define VREF_MV 5000UL #define DIVIDER_RATIO 6UL #define ADC_SAMPLES 32U static const uint8_t segment_codes[10] = { 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F }; static volatile uint8_t display[4] = {0, 0, 0xBF, 0x3F}; ISR(TIMER2_OVF_vect) { static uint8_t phase = 0; uint8_t digit = phase >> 1; uint8_t group = (phase & 1U) ? 0xF0 : 0x0F; PORTB |= DIGIT_MASK; PORTD = 0; PORTD = display[digit] & group; PORTB &= (uint8_t)~(1U << digit); phase = (phase + 1U) & 0x07; } static uint16_t adc_read(void) { ADCSRA |= (1U << ADSC); while (ADCSRA & (1U << ADSC)) { } uint8_t low = ADCL; uint8_t high = ADCH; return ((uint16_t)high << 8) | low; } static void display_voltage(uint16_t decivolts) { uint8_t next[4]; next[0] = 0; next[1] = decivolts >= 100U ? segment_codes[decivolts / 100U] : 0; next[2] = segment_codes[(decivolts / 10U) % 10U] | 0x80; next[3] = segment_codes[decivolts % 10U]; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { for (uint8_t i = 0; i < 4; ++i) { display[i] = next[i]; } } } int main(void) { cli(); UCSR0B = 0; TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TCCR0A = 0; TCCR0B = 0; TCCR1A = 0; TCCR1B = 0; TCCR2A = 0; TCCR2B = 0; PORTB |= DIGIT_MASK; DDRB |= DIGIT_MASK; PORTD = 0; DDRD = 0xFF; DDRC &= (uint8_t)~(1U << PC0); PORTC &= (uint8_t)~(1U << PC0); DIDR0 |= (1U << ADC0D); ADMUX = (1U << REFS0); ADCSRB = 0; ADCSRA = (1U << ADEN) | (1U << ADPS2) | (1U << ADPS1) | (1U << ADPS0); TCNT2 = 0; TIFR2 = (1U << TOV2); TIMSK2 = (1U << TOIE2); TCCR2B = (1U << CS22); sei(); (void)adc_read(); while (1) { uint32_t sum = 0; for (uint8_t i = 0; i < ADC_SAMPLES; ++i) { sum += adc_read(); } uint32_t divisor = (uint32_t)ADC_SAMPLES * 1024UL * 100UL; uint16_t decivolts = (uint16_t)( (sum * VREF_MV * DIVIDER_RATIO + divisor / 2UL) / divisor ); display_voltage(decivolts); _delay_ms(100); } }