/*
 * rs485.c
 *
 * Created: 24/09/2016 19:15:39
 *  Author: Ledo
 */ 

#include "rs485.h"


void rs485_init(void)
{
	
	// Assign GPIO to USART.
	gpio_enable_module(USART_GPIO_MAP,
	sizeof(USART_GPIO_MAP) / sizeof(USART_GPIO_MAP[0]));

	// Initialize USART in RS232 mode.
	usart_init_rs232(USART, &USART_OPTIONS,48000000);
	sysclk_enable_peripheral_clock(USART);
	INTC_register_interrupt(&usart_irq, AVR32_USART0_IRQ, AVR32_INTC_INT0);
	// Enable USART Rx interrupt.
	USART->ier = AVR32_USART_IER_RXRDY_MASK;
	
}




/* Transmite comandos y datos al lcd  */
void send_to_lcd(char cmd)
{
	int i;
	int cksum = 0;
	unsigned char * s;
	unsigned char * d;
	rs4_tx_buffer[0] = 2;//usart.dirRs485;
	rs4_tx_buffer[1] = cmd;
	s = &lcd_buffer_H[0];
	d = &rs4_tx_buffer[2];
	for(int k=0;k<16;k++)
	* d++ = * s++;
	s = &lcd_buffer_L[0];
	for(int k=0;k<16;k++)
	* d++ = * s++;
	for(i=0;i<RS485_TX_BUFFLENGH -2;i++)
	cksum += rs4_tx_buffer[i];
	rs4_tx_buffer[RS485_TX_BUFFLENGH -2] = (unsigned char) (cksum % 256);
	rs4_tx_buffer[RS485_TX_BUFFLENGH -1] = (unsigned char) (cksum >> 8);
	for (i=0;i<RS485_TX_BUFFLENGH;i++)
	{
		
		while(!usart_tx_ready(USART));
		USART->thr = (rs4_tx_buffer[i] << AVR32_USART_THR_TXCHR_OFFSET) & AVR32_USART_THR_TXCHR_MASK;
	}
	
} // end rs485_tx()



__attribute__((__interrupt__))
static void usart_irq(void)
{
	 volatile unsigned int status = USART->csr;
	 volatile int rxByte;
	 // Receiver ready
	 if ((status & AVR32_USART_IER_RXRDY) == AVR32_USART_IER_RXRDY) 
	 {
	    rxByte = (USART->rhr & AVR32_USART_RHR_RXCHR_MASK) >> AVR32_USART_RHR_RXCHR_OFFSET;
	    rs4_rx_buffer[rx_index++] = rxByte;
	    if(rx_index >= RS485_RX_BUFFLENGH)
	    {
		   rx_index = 0; // set a breakpoint here to view buffer
		   datos_listos = true;
	    }
		 
		 
	 }


	//rxByte = (USART->rhr & AVR32_USART_RHR_RXCHR_MASK) >> AVR32_USART_RHR_RXCHR_OFFSET;
	

}

