/*
 * timers_pwm_lab.ino
 * ARGYNIX Skills (worldskills.blog), lesson "Timers and PWM at register level".
 * The same program as timer1_pwm_avr.c, as an Arduino sketch: it runs in ARGYNIX Lab
 * and in the Arduino IDE on a real Uno. Save it in a folder named timers_pwm_lab.
 *
 *   D9  (OC1A): 1 kHz PWM from Timer1, mode 14. Duty follows the knob on A0.
 *   D13:        2 Hz blink from our own 1 ms tick on Timer2 (Timer0 stays with millis()).
 *   Serial:     the duty in percent, twice a second, at 115200 baud.
 *
 * Do not use analogWrite() on pins 9, 10, 3 or 11 in this sketch: Timer1 and Timer2
 * are ours now.
 */
#include <util/atomic.h>

#define PWM_TOP 15999u /* 16 MHz / (1 x 16000) = 1000 Hz */

static volatile uint32_t ms_ticks;
static uint16_t duty_permille;

ISR(TIMER2_COMPA_vect)
{
  ms_ticks++;
}

static uint32_t ticks_now(void)
{
  uint32_t t;
  ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
  {
    t = ms_ticks; /* 32 bits: read with interrupts held off */
  }
  return t;
}

static void tick_init(void)
{
  TCCR2A = (1 << WGM21);  /* CTC */
  TCCR2B = (1 << CS22);   /* clk/64: 250 kHz */
  OCR2A = 249;            /* 250 counts = 1 ms */
  TIMSK2 = (1 << OCIE2A);
}

static void pwm_init(void)
{
  DDRB |= (1 << DDB1);    /* D9 */
  /* Mode first, timer stopped: the core leaves Timer1 in 8-bit PWM, where writing OCR1A
   * cuts off its high bits. Then TOP and the compare value, then start. */
  TCCR1B = 0;
  TCCR1A = (1 << WGM11);  /* mode 14 with the two bits in TCCR1B; output connected later */
  TCCR1B = (1 << WGM13) | (1 << WGM12);
  ICR1 = PWM_TOP;
  OCR1A = 0;
  TCNT1 = 0;
  TCCR1B |= (1 << CS10);  /* clk/1 */
}

static void pwm_set_permille(uint16_t permille)
{
  if (permille == 0) {
    TCCR1A &= ~(1 << COM1A1); /* a true 0 %: disconnect and hold LOW */
    PORTB &= ~(1 << PORTB1);
    return;
  }
  if (permille > 1000u) permille = 1000u;
  uint32_t counts = ((uint32_t)permille * (PWM_TOP + 1u)) / 1000u;
  OCR1A = (uint16_t)(counts - 1u); /* duty = (OCR1A + 1) / (TOP + 1) */
  TCCR1A |= (1 << COM1A1);
}

static void adc_init(void)
{
  ADMUX = (1 << REFS0);   /* AVcc reference, A0 */
  ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); /* 125 kHz */
  DIDR0 = (1 << ADC0D);
}

static uint16_t adc_read(void)
{
  ADCSRA |= (1 << ADSC);
  while (ADCSRA & (1 << ADSC)) {
  }
  return ADC;
}

void setup()
{
  Serial.begin(115200);
  DDRB |= (1 << DDB5);    /* D13 */
  tick_init();
  pwm_init();
  adc_init();
}

void loop()
{
  static uint32_t last_pwm = 0, last_led = 0, last_print = 0;
  uint32_t now = ticks_now();

  if (now - last_pwm >= 10u) {
    last_pwm += 10u;
    uint16_t raw = adc_read();
    duty_permille = (uint16_t)(((uint32_t)raw * 1000u + 511u) / 1023u);
    pwm_set_permille(duty_permille);
  }

  if (now - last_led >= 250u) {
    last_led += 250u;
    PORTB ^= (1 << PORTB5);
  }

  if (now - last_print >= 500u) {
    last_print += 500u;
    Serial.print(F("duty "));
    Serial.print(duty_permille / 10u);
    Serial.print('.');
    Serial.print(duty_permille % 10u);
    Serial.println(F(" %"));
  }
}
