/*  UART implementation using the ATMEL ATMega32 MCU
    By - Nandan Banerjee (08/CSE/15)
         NIT Durgapur
         16/06/2010
*/

#define UBRR 5      			// UART Baud rate - 115200 bps

void uart_init()
{
    UBRRH = (uint8_t)(UBRR >> 8);
    UBRRL = (uint8_t)(UBRR);

    UCSRB = ((1<<RXEN) | (1<<TXEN) | (1<<RXCIE));   // Enable Receiver, Transmitter, Receive Interrupt
    UCSRC = ((1<<URSEL) | (1<<UCSZ1) | (1<<UCSZ0));     // 8N1 data frame
}

void uart_putc(unsigned char c)
{
    // wait until UDR ready
	while(!(UCSRA & (1 << UDRE)));
	UDR = c;    // send character
}

void uart_puts(const char *s)
{
	//  loop until *s != NULL
	while(pgm_read_byte(s) != 0x00)
		uart_putc(pgm_read_byte(s++));
}

void uart_write_int16(int16_t in)
{
	uint8_t started = 0;
	uint16_t pow = 10000;
	
	while (pow >= 1)
	{
		if (in/pow > 0 || started || pow == 1)
		{
			uart_putc((uint8_t) (in/pow) + '0');
			started = 1;
			in = in % pow;
		}
		pow = pow / 10;
	}
}
