Help - Atmega328p, converting a PWM servo code from pin9 to pin6 I found a working code that uses pin9 (PB1) on my Arduino for controlling a Servo, but in my project, an ultrasonic sensor is already using that pin/timer. I want to convert the code to use pin6 (PD6), changed the registers according to the atmega's datasheet, but it doesn't work. Need help :/



The code should allow me to turn a servo using a potentiometer.

#define F_CPU 16000000 //16MHz
#include &lt;avr/io.h&gt;
#include &lt;util/delay.h&gt;
#include &lt;avr/interrupt.h&gt;
#include &lt;stdlib.h&gt;

#define PWM_PRESCALLER 64
#define ICR_MAX (long double)F_CPU/PWM_PRESCALLER/50
#define OCR_MIN (float)ICR_MAX/37.5 // /8.75
#define OCR_MAX (float)ICR_MAX/8.7 // 37.5

volatile unsigned long adc_val=0;
volatile unsigned long counter=0;
unsigned long curr_adc=0;

ISR (ADC_vect)
{
adc_val += ADC;
counter++;
}

int main(void)
{
    DDRD |= (1&lt;&lt;DDD6);
    ICR1 = ICR_MAX;
    OCR0A = OCR_MIN;
    TCCR0A = (1 &lt;&lt; COM1A1) | (1&lt;&lt;WGM00) | (1&lt;&lt;WGM01);
    TCCR0B = (1&lt;&lt;WGM02) | (1&lt;&lt;CS01) | (1&lt;&lt;CS00);
    ADMUX = (1 &lt;&lt; REFS0);
    ADCSRA = (1 &lt;&lt; ADEN)|(1 &lt;&lt; ADATE)|(1 &lt;&lt; ADIE)|(1&lt;&lt;ADPS2)|(1&lt;&lt;ADPS1)|(1&lt;&lt;ADPS0);

    sei();
    ADCSRA |= (1&lt;&lt;ADSC);

    while(1)
    {
        if(counter &gt;= 1000)
        {
            cli();
            unsigned long round_val = round(adc_val / counter);
            adc_val=0;
            counter=0;
            if(abs(round_val - curr_adc) &gt; 1)
            {
                curr_adc = round_val; 
            }
            long double ocr = OCR_MIN + ((long double)curr_adc * (OCR_MAX - OCR_MIN)/1024);

            OCR0A = (int)round(ocr);
            sei();
        }
    } 
}
PORTB bit 6 is controlled with TIMER0 while PORTB bit 1 is controlled with TIMER1.  Therefore you need to change the timer variables appropriately.  One mistake in your code is that you leave ICR1.  It should be OCRA if you want to use TIMER0.