title: Pulse width modulation (PWM) on AVR Studio
body: <p>I'm trying to use PWM for an LED on an ATmega8, any pin of port B. Setting up timers has been a annoying, and I don't know what to do with my OCR1A. Here's my code, and I'd love some feedback.</p>
  
  <p>I'm just trying to figure out how use PWM. I know the concept, and OCR1A is supposed to be the fraction of the whole counter time I want the pulse on.</p>
  
  <pre><code>#define F_CPU 1000000  // 1 MHz
  
  #include &lt;avr/io.h&gt;
  #include &lt;avr/delay.h&gt;
  #include &lt;avr/interrupt.h&gt;
  
  int main(void){
  
      TCCR1A |= (1 &lt;&lt; CS10) | (1 &lt;&lt; CS12) | (1 &lt;&lt; CS11);
      OCR1A = 0x0000;
      TCCR1A |= ( 0 &lt;&lt; WGM11 ) | ( 1 &lt;&lt; WGM10 ) | (WGM12 &lt;&lt; 1) | (WGM13 &lt;&lt; 0);
      TCCR1A |= ( 1 &lt;&lt; COM1A0 ) | ( 0 &lt;&lt; COM1A1 );
      TIMSK |= (1 &lt;&lt; TOIE1); // Enable timer interrupt
      DDRB = 0xFF;
      sei(); // Enable global interrupts
      PORTB = 0b00000000;
  
      while(1)
      {
          OCR1A = 0x00FF; //I'm trying to get the timer to alternate being on for 100% of the time,
          _delay_ms(200);
          OCR1A = 0x0066; // Then 50%
          _delay_ms(200);
          OCR1A = 0x0000; // Then 0%
          _delay_ms(200);
      }
  }
  
  ISR (TIMER1_COMA_vect)  // timer0 overflow interrupt
  {
      PORTB =~ PORTB;
  }
  </code></pre>