// diparithmetic.c
// for NerdKits with ATtiny26L
// hevans@mit.edu

// F_CPU defined for delay.c
#define F_CPU 8000000UL	// 8MHz

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

#include "lcd.h"

// PIN DEFINITIONS:
//
// PA4 -- LCD RS (pin 4)
// PA5 -- LCD E (pin 6)
// PB3-6 -- LCD DB4-7 (pins 11-14)

int main() {
  // internal RC oscillator calibration for 8MHz.
  OSCCAL = 176;
  
  // fire up the LCD
  lcd_init();
  lcd_home();

  
  // Set the 6 pins to input mode - Two 3 bit numbers  

  DDRA &= ~(1<<PA0); // set PA0 as input
  DDRA &= ~(1<<PA1); // set PA1 as input
  DDRA &= ~(1<<PA2); // set PA2 as input
  DDRA &= ~(1<<PA3); // set PA3 as input
  DDRA &= ~(1<<PA6); // set PA0 as input
  DDRA &= ~(1<<PA7); // set PA0 as input
	  
  // turn on the internal resistors for the pins

  PORTA |= (1<<PA0); // turn on internal pull up resistor for PA0
  PORTA |= (1<<PA1); // turn on internal pull up resistor for PA1
  PORTA |= (1<<PA2); // turn on internal pull up resistor for PA2
  PORTA |= (1<<PA3); // turn on internal pull up resistor for PA3
  PORTA |= (1<<PA6); // turn on internal pull up resistor for PA6
  PORTA |= (1<<PA7); // turn on internal pull up resistor for PA7
  

  // declare the variables to represent each bit, of our two 3 bit numbers
  uint8_t a1;
  uint8_t a2;
  uint8_t a3;

  uint8_t b1;
  uint8_t b2;
  uint8_t b3;
  
  while(1){
  
          // (PINA & (1<<PA0)) returns 8 bit number, 0's except position PA0 which is the bit we want
          // shift it back by PA0 to put the bit we want in the 0th position.

	  a1 = (PINA & (1<<PA0)) >> PA0;
	  a2 = (PINA & (1<<PA1)) >> PA1;
	  a3 = (PINA & (1<<PA2)) >> PA2;
	  
	  b1 = (PINA & (1<<PA3)) >> PA3;
	  b2 = (PINA & (1<<PA6)) >> PA6;
	  b3 = (PINA & (1<<PA7)) >> PA7;
	  
     	  lcd_home();
	  lcd_write_string(PSTR("Adding: "));
	  lcd_write_int16((a1<<2) + (a2<<1) + a3);
	  lcd_write_data('+');
	  lcd_write_int16((b1<<2) + (b2<<1) + b3);
	  lcd_write_string(PSTR("        "));
	  
	  lcd_line_two();
	  lcd_write_string(PSTR("Equals: "));
	  lcd_write_int16(  ((a1<<2) + (a2<<1) + a3)  +  ((b1<<2) + (b2<<1) + b3) );
	  lcd_write_string(PSTR("        "));
	  
	  delay_ms(500);
	  
  }
  return 0;
}
