#ifndef F_CPU #define F_CPU 1000000UL #endif #include #include #include #include static uint16_t adc_read(void) { ADCSRA |= (1U << ADSC); while (ADCSRA & (1U << ADSC)) { } uint8_t low = ADCL; /* Read ADCL before ADCH. */ uint8_t high = ADCH; return ((uint16_t)high << 8) | low; } int main(void) { /* Requires 16 MHz oscillator, CKDIV8 disabled (stock Uno). Runtime CPU = 16 MHz / 16 = 1 MHz; F_CPU is 1000000. */ clock_prescale_set(clock_div_16); UCSR0B = 0; /* PD0 and PD1 are GPIO here. */ DDRD = 0xFF; PORTD = 0; DDRC &= (uint8_t)~(1U << PC0); PORTC &= (uint8_t)~(1U << PC0); DIDR0 = (1U << ADC0D); ADMUX = (1U << REFS0); /* AVcc, ADC0, right-adjusted. */ ADCSRB = 0; /* No automatic trigger. */ ADCSRA = (1U << ADEN) | (1U << ADPS1) | (1U << ADPS0); (void)adc_read(); /* Discard first conversion. */ while (1) { uint16_t value = adc_read(); uint8_t level = (uint8_t)(((uint32_t)value * 8U + 511U) / 1023U); PORTD = level == 8U ? 0xFFU : (uint8_t)((1U << level) - 1U); _delay_ms(20); } }