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 <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#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<<DDD6);
ICR1 = ICR_MAX;
OCR0A = OCR_MIN;
TCCR0A = (1 << COM1A1) | (1<<WGM00) | (1<<WGM01);
TCCR0B = (1<<WGM02) | (1<<CS01) | (1<<CS00);
ADMUX = (1 << REFS0);
ADCSRA = (1 << ADEN)|(1 << ADATE)|(1 << ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
sei();
ADCSRA |= (1<<ADSC);
while(1)
{
if(counter >= 1000)
{
cli();
unsigned long round_val = round(adc_val / counter);
adc_val=0;
counter=0;
if(abs(round_val - curr_adc) > 1)
{
curr_adc = round_val;
}
long double ocr = OCR_MIN + ((long double)curr_adc * (OCR_MAX - OCR_MIN)/1024);
OCR0A = (int)round(ocr);
sei();
}
}
}
analogRead
each time through your loop? And use the Servo library to control the servo?