#ifndef _UART_H_

#define _UART_H_

 

// Helpful defines

#define uart_buffer r_buffer

#define uart_ready r_ready

 

// RXC ISR variables                                             

unsigned char r_index;  // current string index

unsigned char r_buffer[16];   // input string

unsigned char r_ready;  // flag for receive done

unsigned char r_char;  // current character 

 

// TX ISR variables                

// Set up a circular buffer to output the strings to

#ifndef TRANSMIT_BUFFER_SIZE

#define TRANSMIT_BUFFER_SIZE 21

#endif

 

unsigned char t_index;  // current string index

unsigned char t_end; // index of end

unsigned char t_buffer[TRANSMIT_BUFFER_SIZE];   //output string

unsigned char t_char;  //current character

 

// Instruction length

#ifndef INST_LENGTH

#define INST_LENGTH 6

#endif                     

                

// XMIT output DDR

#ifndef XMIT_DDR

#define XMIT_DDR DDRD.4

#endif

 

// XMIT output port

#ifndef XMIT_OUT

#define XMIT_OUT PORTD.4

#endif

 

// UART receive byte ready interrupt

interrupt [USART_RXC] void uart_rec(void)

{      

      // Set the XMIT line to recieve

      XMIT_OUT = 0;

     

      // Read in a character

      r_char=UDR;

     

      // Add the character to the receive buffer

      r_buffer[r_index++]=r_char;

           

      // If we have received a full instruction

      if (r_index == INST_LENGTH)

    {

            // Set the message ready flag

            r_ready=1; 

 

            // Turn off the receive interrupt

            UCSRB.7=0;

      }

}

 

// UART data register empty interrupt

interrupt [USART_DRE] void uart_tx(void)

{               

      // Set the XMIT line to transmit

      XMIT_OUT = 1;

     

      // Read in a char from the buffer

      t_char = t_buffer[t_index];

 

      // Increase and mod the index, to make this a circular buffer

      t_index = (t_index + 1) % TRANSMIT_BUFFER_SIZE;

                    

      // If we have reached the end of the string

      if (t_index == t_end)  

      {

            // Turn off the transmit interrupt

            UCSRB.5 = 0;

      }

 

      // Otherwise write it to the UART

      else UDR = t_char;

 

      // Set the XMIT line back to receive

      XMIT_OUT = 0;

}

 

// Function to setup the receive interrupt

void uart_gets_int(void)

{

      // Reset the variables

      r_ready=0;

      r_index=0;

 

      // Enable the receive ISR

      UCSRB.7=1;

}

 

 

// Function to initialize the UART

void uart_init(unsigned char newBPS)

{

      // Setup the UART registers

      UCSRB = 0x18;

      UBRRL = newBPS;

     

      // Setup the XMIT line

      XMIT_DDR = 1;

}

 

#endif