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


#define CLRSCR		12		// terminal torlese

#define USART_BAUDRATE 9600		// kommunikacios sebesseg
#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
unsigned volatile char ReceivedByte;	// fogadott byte

// Varakozik a soros port 'kesz' allapotara
void wait_rs232(void)
{
    while (!(UCSRA & (1 << UDRE)));
}

// Egyetlen byte kuldese
void send_byte(unsigned char abyte)
{
    wait_rs232();
    UDR = abyte;
}

// Belso hasznalatra. 0..f -ig a szamerteket kuldi ki betukent
void send_nibble2hex(unsigned char abyte)
{
    if (abyte <= 9)
	send_byte('0'+abyte);
    else
	send_byte('a'+(abyte-10));
}

// hexa szamot kuld 00..ff
void send_byte2hex(unsigned char abyte)
{
    send_nibble2hex((abyte&0xf0)>>4);
    send_nibble2hex( abyte&0x0f);
}

void send_word2hex(unsigned int aword)
{
	send_byte2hex((aword&0xff00)>>8);
	send_byte2hex((aword&0x00ff));
}

// szoveglanc kuldese '0' lezarassal
void send_string(unsigned char *s)
{
    while (*s)
    {
	send_byte(*s);
	s++;
    }
}

// rs232 megszakitas kezelo. Elmenti a kapott byte-ot, es echo-t kuld
ISR(USART_RXC_vect)
{
 ReceivedByte = UDR; // Fetch the recieved byte value into the variable "ByteReceived"
// UDR = ReceivedByte; // Echo back the received byte back to the computer
}

// rs232 inditasa
void init_rs232(void)
{
    UCSRB |= (1 << RXEN) | (1 << TXEN);   // Turn on the transmission and reception circuitry
    UCSRC |= (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1); // Use 8-bit character sizes

    UBRRL = BAUD_PRESCALE; // Load lower 8-bits of the baud rate value into the low byte of the UBRR register
    UBRRH = (BAUD_PRESCALE >> 8); // Load upper 8-bits of the baud rate value into the high byte of the UBRR register

    UCSRB |= (1 << RXCIE); // Enable the USART Recieve Complete interrupt (USART_RXC)
}


