/*
 * rs485.c
 *
 * Created: 11/06/2018 15:05:07
 *  Author: Ledo
 */ 
#include "asf.h"


uint8_t rs4_rxbuffer[RS4_BUFFER_LENGHT];
uint8_t rs4_txbuffer[RS4_BUFFER_LENGHT];
uint8_t rs4_rx_index;
uint8_t * rs4_rx_pointer;
bool rs4_datos_listos;




/**
 * \brief Configure USART in normal (serial rs232) mode, asynchronous,
 * 8 bits, 1 stop bit, no parity, 38400 bauds and enable its transmitter
 * and receiver.
 */
void configure_usart0(void)
{
	const sam_usart_opt_t usart_console_settings = {
		38400,
		US_MR_CHRL_8_BIT,
		US_MR_PAR_NO,
		US_MR_NBSTOP_1_BIT,
		US_MR_CHMODE_NORMAL,
		/* This field is only used in IrDA mode. */
		0
	};

	/* Enable the peripheral clock in the PMC. */
	sysclk_enable_peripheral_clock(ID_USART0);

	/* Configure USART in serial mode. */
	usart_init_rs232(USART0, &usart_console_settings,
			sysclk_get_peripheral_hz());

	/* Disable all the interrupts. */
	usart_disable_interrupt(USART0, 0xffffffff);

	/* Enable the receiver and transmitter. */
	usart_enable_tx(USART0);
	usart_enable_rx(USART0);

	/* Configure and enable interrupt of USART. */
	NVIC_EnableIRQ(USART0_IRQn);
}


/**
 * \brief Interrupt handler for USART.
 * 
 */
void USART0_Handler(void)
{
	uint32_t ul_status;

	/* Read USART Status. */
	ul_status = usart_get_status(USART0);
	/* Transfer without PDC. */
	if (ul_status & US_CSR_RXRDY) 
	{
		usart_getchar(USART0, (uint32_t *)&rs4_rx_pointer);
		//usart_write(USART0, gs_ul_read_buffer);
		rs4_rxbuffer[rs4_rx_index] = * rs4_rx_pointer;
		rs4_rx_index++;
		if(rs4_rx_index >= 4)
		{
			rs4_rx_index = 0;
			rs4_datos_listos = true;
		}
	}
	
}

void Usart0_sendBytes(uint8_t bytes)
{
      pio_set_pin_high(RS4_DE_PIN);
	  delay_us(50);
	  for (uint8_t i=0;i<bytes;i++)
	  {
		  usart_putchar(USART0,rs4_txbuffer[i]);
	  }
	  while(!usart_is_tx_buf_end(USART0));
      pio_set_pin_low(RS4_DE_PIN);
	
};

