// initialload.c
//
// Aaron Melhorn
// 05/18/10

#include <stdio.h>

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

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

// PIN DEFINITIONS:
// PB5 - SCK
// PB4 - MISO (Master In Slave Out)
// PB3 - MOSI (Master Out Slave In)
// PB2 SS pin for slave panels

uint8_t data;

//Sets the Master Chips Inputs and Outputs
void master_init(){
  
  /* Set MOSI and SCK output, all others input */
  DDRB = (1<<PB3)|(1<<PB5);
  /* Enable SPI, Master, set clock rate fck/16 */
  SPCR = (1<<SPE)|(1<<MSTR);
  SPCR &= ~ ( (1<<SPR1) | (1<<SPR0) );
  SPSR &= ~ (1<<SPI2X);
  

  //set the SS pins we are using as outputs
  DDRB |= (1<<PB2);
  
  //set the SS pin logic high (slave not active)
  PORTB |= (1<<PB2);
 
}


//Ready the POT IC for Commands (active)
void activate_POT(){
  PORTB &= ~(1<<PB2);
  delay_us(5);
}

//Turn off the chip from recieving commands (not active)
void deactivate_POT(){
  PORTB |= (1<<PB2);
  delay_us(5);
}


void data_set() {
  activate_POT();

  /* Start transmission */
  SPDR = data;
  
  /* Wait for transmission complete */
  while(!(SPSR & (1<<SPIF)))
  ;
  
  deactivate_POT();
}


void doItA() {
printf_P(PSTR("\r\n-"));
	data = 4;
	
	data_set();

}

void doItB() {
printf_P(PSTR("\r\n+"));
	data = 8;
	
	data_set();

}

int main() {

  //This is for the LED
  DDRC |= (1<<PC4);
  
  DDRC |= (1<<PC3);

  master_init();
  
  //Turn on an LED and we are ready to go...
  PORTC |= (1<<PC4);
  
  //Turn on the IC
  PORTC |= (1<<PC3);
  
  // activate interrupts
  sei();

  // init serial port
  //This if For Computer Input
  uart_init();
  FILE uart_stream = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
  stdin = stdout = &uart_stream;

  char x=' ';
  printf_P(PSTR("\r\nIt's a go!"));
 
  
  while(1) {
	x = uart_read();
	
	//Controls
	if(x == 'u') {
		doItA();
	}
	else if(x == 'i') {
		doItB();
	
	}
	else {
		//Don't Do Anything...
	}
	
  }
  return 0;
}


