/*
  Read ADC2 (PB2) and output servo signal on PB0 .
 */

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{   ADMUX = 2;// ADC channel 2
    DIDR0 = (1<<ADC2D);    // Disable digital input on PB2
    ADCSRA = (1<<ADEN) | (1<<ADPS1) | (1<<ADPS0);// Enable ADC, presc 1:8 for 125kHz ADC-clock
 
    DDRB = (1<<PB0) ; // PB0  output.
    
    uint16_t adc4;

    // Timer0 50Hz PWM, 1us tick, mode 14 with ICR0 as TOP.
    ICR0 = 19999; // 1MHz / 50Hz - 1
  //   OCR0A = 1500;  // Start with 1,5 ms pulse-width
    TCCR0A = (1<<COM0A1)| (1<<WGM01);  // OC0A non inverting PWM, mode bit 1
    TCCR0B = (1<<WGM03) | (1<<WGM02) | (1<<CS00);     // mode bits 2 and 3, presc 1:1

    OCR0A = 2010 ;    // trottle max voor esc
    _delay_ms(300); //  is ongeveer 2,5 seconden
    OCR0A = 990 ;   // trottle min voor esc
    _delay_ms(300);

do { ADCSRA |= (1<<ADSC);          // Start a conversion
     while (ADCSRA & (1<<ADSC));   // wait until it's finished
    } while ( ADCL > 230 ); // wacht tot stand potmeter is laag

  
    while(1)    {
  uint8_t i;

  // Take four ADC samples, add them in adc4
  for (i = 0, adc4 = 0; i < 4; i++)
    {   ADCSRA |= (1<<ADSC);          // Start a conversion
        while (ADCSRA & (1<<ADSC));   // wait until it's finished
        adc4 += ADCL;
    }

  // Set PWM to 990 to 2010 ms from ADC.    4 x 255 = 1020
  OCR0A = 2010 - adc4; // potmeter spanning gaat van hoog naar laag , vandaar omkeren

    }
}
