#define TIMER0_PRESCALER 64
#define TIMER0_FREQUENCY 1000 // Hz
#define PWM_PERIOD_MS 20 //PWM-period in milli seconds
#define TIMER_CLOCKS 16000000/8 //prescaled timer clocks per second of timer 1
#define TIMER_CLOCKS_PER_MS TIMER_CLOCKS/1000
#define TIMER_CLOCKS_PER_PWM_PERIOD PWM_PERIOD_MS*TIMER_CLOCKS_PER_MS
#define LEFT_POS 1.00*TIMER_CLOCKS_PER_MS-1 // 1.0 ms for left position
#define MIDDLE_POS 1.48*TIMER_CLOCKS_PER_MS-1 // 1.5 ms for middle position
#define RIGHT_POS 2.00*TIMER_CLOCKS_PER_MS-1 // 2.0 ms for right position
#define POS_MIN 0.57*TIMER_CLOCKS_PER_MS-1
#define POS_MAX 2.53*TIMER_CLOCKS_PER_MS-1
unsigned int timer0_counter = 0;
void setup()
{
//CTC-Mode of Timer0
OCR0A = 249;
TCCR0A = (1 << WGM01); //CTC-Mode TOP-Value = OCR0A
TCCR0B = (1 << CS01) | (1 << CS00); //Prescaler = 64
TIMSK0 = (1 << OCIE0A);
TIFR0 = (1 << OCF0A);
//FAST PWM SETTINGS USING TIMER1
DDRB |= (1 << PB1); //set PB1 for OC1A to output mode
TCCR1A = (1 << COM1A1) | (1 << WGM11); //Clear OC1A on compare match, set OC1A at BOTTOM value of TCNT1
TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11); //Fast PWM in Mode 14, prescaler = 8
OCR1A = RIGHT_POS; //Compare value for pulse width equal to servo middle position
ICR1 = TIMER_CLOCKS_PER_PWM_PERIOD; //Top value to set pwm-period
sei();
}
void loop()
{
}
ISR(TIMER0_COMPA_vect)
{
if(++timer0_counter == TIMER0_FREQUENCY)
{
timer0_counter = 0;
if(OCR1A == RIGHT_POS) OCR1A = LEFT_POS;
else OCR1A = RIGHT_POS;
}
}