/* Placed into the Public Domain by posting to hyiq.org */
#include <Arduino.h>
#include <avr/io.h>
#include <util/delay.h>

int32_t period_on;
int32_t period_off;
register uint8_t us;

void setPWMPeriod( double frequency, double duty ) {
  double period;
  period = ((double)F_CPU/frequency);
  period_on = period*duty;
  period_off = period - period_on;
}

#define DELAY_PRECISE(cycles) { \
  int32_t counter = cycles; \
  while ( counter > 8)  { \
      us = TCNT0; \
      TCNT0 = 0; \
      counter -= us + 2; \
  } \
  asm volatile("nop"); \
  asm volatile("nop"); \
}

int main()
{
  static_assert(F_CPU==16000000, "Code optimized for 16mhz");

  cli();
  TCCR0B &= ~(_BV(CS00)|_BV(CS01)|_BV(CS02));
  TCCR0B |= _BV(CS00);
  DDRD |= _BV(PD6);
  PORTD &= ~_BV(PD6);
  setPWMPeriod(1000, 0.25);

  register uint8_t us;
  TCNT0 = 0;
  while ( 1 )
  {
    DELAY_PRECISE(period_off);
    PORTD ^= _BV(PD6);
    DELAY_PRECISE(period_on);
    PORTD ^= _BV(PD6);
  }

  return 0;
}

