// backlight.c
// for NerdKits with ATmega168
// mrobbins@mit.edu

#define F_CPU 14745600

#include <stdio.h>

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <inttypes.h>

#include "../libnerdkits/delay.h"
#include "../libnerdkits/lcd.h"
#include "../libnerdkits/uart.h"

// PIN DEFINITIONS:
//
// PB1 -- OC1A -- backlight high-speed switchy thing (nFET gate)
//		used to generate the high voltage supply
// PB3 -- OC2A -- backlight low-speed switchy thing (nFET gate)
//		used to pulse the AC to the electroluminescent

int main() {
  // PB1,3 as output
  DDRB |= (1<<PB1) | (1<<PB2) | (1<<PB3);
  
  // Timer1: Toggle CTC, 10-bit, non-inverting, clocked from CLK/1
  TCCR1A = (1<<COM1A0);
  TCCR1B = (1<<WGM12) | (1<<CS10);
  OCR1A = 51; // 141 kHz
  
  // Timer2: Toggle CTC, clocked from CLK/1024
  TCCR2A = (1<<COM2A0) | (1<<WGM21);
  TCCR2B = (1<<CS22) | (1<<CS21) | (1<<CS20);
  OCR2A = 40; // 175 Hz
  
  // init serial port
  uart_init();
  FILE uart_stream = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
  stdin = stdout = &uart_stream;

  char x;
  //			      123456789012345678901234
  const char *lineone = PSTR(" NerdKits LCD Backlight ");
  const char *linetwo = PSTR("http://www.NerdKits.com/");
  
  // fire up the LCD
  lcd_init();
  lcd_home();

  // write lines
  lcd_home();
  lcd_write_string(lineone);
  lcd_line_two();
  lcd_write_string(linetwo);

  double freq_a, freq_b;
  // main loop
  while(1) {
    // allow user to adjust timings via serial port
    if(uart_char_is_waiting()) {
      x = uart_read();
      if(x == 'w') {
        OCR1A += 1;
      } else if(x=='q') {
        OCR1A -= 1;
      } else if(x=='s') {
        OCR2A += 1;
      } else if(x=='a') {
        OCR2A -= 1;
      }
      
      // convert to human-readable frequencies
      freq_a = F_CPU; freq_a = freq_a / 2.0 / (OCR1A+1.0);
      freq_b = F_CPU; freq_b = freq_b / 2.0 / 1024.0 / (OCR2A+1.0);
      
      printf_P(PSTR("OCR1A=%3u, %.0f Hz\t\t|\tOCR2A=%3u, %.2f Hz\r\n"), OCR1A, freq_a, OCR2A, freq_b);
    }
  }

  return 0;
}
