#include "display.h"

void display_next();

//Charset
#define DOT (1<<8)
//                            HGFEDCBA
const uint8_t digits[10] = {0b00111111,
							0b00000110,
							0b01011011,
							0b01001111,
							0b01100110,
							0b01101101,
							0b01111101,
							0b00000111,
							0b01111111,
							0b01100111};
const uint8_t splash[4] = {0b00111000, 0b00111111, 0b00111110, 0b01110011};

//External Buffers
uint16_t value = 0;
uint8_t dots = 0;
//Buffers
uint8_t values_buf[4] = {0};
uint8_t display_buf[4] = {0};


void timer_setup(){
	//compare match register = [ 16,000,000Hz/ (prescaler * desired interrupt frequency) ] - 1
	//frequency = 900Hz, prescaler = 256 (0b100), register = 68
	cli();//stop interrupts
	
	TCCR1A = 0;// set entire TCCR1A register to 0
	TCCR1B = 0;// same for TCCR1B
	TCNT1  = 0;//initialize counter value to 0
	// set compare match register for 1hz increments
	OCR1A = 128;
	// turn on CTC mode
	TCCR1B |= (1 << WGM12);
	// Set CS12 bit for 256 prescaler
	TCCR1B |= (1 << CS12);
	// enable timer compare interrupt
	TIMSK1 |= (1 << OCIE1A);

	sei();//allow interrupts
}



// Load splash screen
void splashscreen(){
	uint8_t i;
	
	for(i=0; i<4; i++)
		display_buf[i] = splash[i];
}

// Convert to BCD
void convert(){
	values_buf[0] = (uint8_t)(value/(uint16_t)1000);
	values_buf[1] = (uint8_t)(value/100 - (uint16_t)(values_buf[0])*10);
	values_buf[2] = (uint8_t)(value/10 - (uint16_t)(values_buf[0])*100 - (uint16_t)(values_buf[1])*10);
	values_buf[3] = (uint8_t)(value%10);
}

// Fill display buffer with new values
void fillBuffer(){
	uint8_t i;
	for(i=0; i<4; i++){
		display_buf[i] = digits[values_buf[i]];
		display_buf[i] |= ((dots >> (3-i)) & 1) ? 0x80:0x00;
	}
}

// Clear display buffer with zeros
void clearBuffer(){
	uint8_t i;
	for(i=0; i<4; i++){
		display_buf[i] = ((dots >> (3-i)) & 1) ? 0x80:0x00;
	}
}



/* Interrupts */

//timer1 interrupt
ISR(TIMER1_COMPA_vect){
	display_next();
}

void display_next(){
	static uint8_t d = 0;
	
	_SET_DIGIT(0x00);
	_SELECT_DIGIT(d);
	_SET_DIGIT(display_buf[d]);
	
	d = (d+1)%4;
}

