/** \file ******************************************************************
* \brief UartDisplay Main File
* 
* \authors 	Dominic Rathje (dominic.rathje@uni-ulm.de)<br>
* 			Christian Degenhart (christian.degenhart@uni-ulm.de)
* \version 1.2
* \note
* - Compiler          : WinAVR 20100110
* - Supported devices : ATMega8
*
* 
*****************************************************************************/

/** \mainpage UartDisplay
 * 
 * Thhis Project implements the Dotmatrix LCD Library written in Assembler
 * and provides a UART INterface to a PC or other Mikrocontrollers.
 * 
 * The Usage is sraight forward, just send a string, terminated by \n. 
 * This string is then displayed on the last line of the screen. 
 * The previous content of the screen is schifted up by one line
 * 
 * See https://wiki.fs-et.de/student-lab/UartDisplay for more details (German).
 * 
 */

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


#include "lcd.h"
#include "uart.h"
#include "button.h"
#include "buzzer.h"

uint8_t cnt=0;
uint8_t cnt2=0;
extern uint8_t scroll;

#define DISPLAY_bp 4
#define BACKLIGHT_bp 5
 


/**  \brief Initializes timer2.
 *  
 * - Prescaler is set to 1024
 * - Overflow Interrput enabled.
 */
inline void timer2_init(void) {
	//Timer zum scrollen
	TCCR2 = (1<<CS22) | (1<<CS21); 					//Clock Select. Prescaler set to 256 (28.8 kHz)
	TIMSK |= (1<<TOIE2); 							//Timer2 Overflow Interrput Enable
}


int main(void) {
	
	uint8_t data;
	
	uart_init();
	button_init();
	buzzer_init();
	
	timer2_init();
	
	// Switch Display and Backlight on
	DDRB |= (1<<DISPLAY_bp) ;
	PORTB &= ~(1<<DISPLAY_bp);
	DDRB |= (1<<BACKLIGHT_bp);
	PORTB &= ~(1<<BACKLIGHT_bp);
	
	sei(); 												// Global Interrput Enable										
	
	lcd_init(); 										// Initialize LCD driver IC
	print_buffer(); 									// Write buffer to display
	
	
	while(1) {
		if(uart_getbyte(&data)) { 						//If there is received data 
			lcd_putchar(data, NULL); 					// 
		}
		
		//~10Hz
		if(scroll && cnt>40) {
			cnt=0;
			lcd_scroll();
		}
		
		//~50Hz
		if(cnt2>1) {
			cnt2=0;
			button_process();
			
		} 
		
	}
}


//112.5Hz
ISR(TIMER2_OVF_vect ){
	cnt++;
	cnt2++;
}


