#include <stdio.h>
#include "system.h"
#include "io.h"
#include "sys/alt_flash.h"
#include "sys/alt_flash_dev.h"
#include "altera_avalon_pio_regs.h"
#include <string.h>
#include <stdlib.h>
#include "sys/alt_stdio.h"
#include "uart.h"
#include "modbus.h"

//extern alt_u8 uart0_tx_state;//0״̬
//int main()
//{
//	//ʼ
//	uart0_tx_state = UART_TX_IDLE;//ʼ״̬־Ϊ
//	UART_HANDLE hUART0;
//	hUART0 = UART_Init(
//			UART_BASE,
//			UART_IRQ_INTERRUPT_CONTROLLER_ID,
//			UART_IRQ,
//			(IRRDY_IRQ_MASK),//򿪽жʹ0X80
//			115200,//ڲ
//			(alt_isr_func)UART0_isr
//		);
//	if (!hUART0) {
////		printf("Failed to init UART0\n");
//	}
//	UARTx_Tx(hUART0, (alt_u8 *)"NIOS II!\n",sizeof("NIOS II!\n"));
//	while(1)
//	{
//		ModBus_ReceieveCMD(hUART0); //ڽж
//	}
//}


alt_u8 data_tmp[1024] = {0};//ڽյʱ
extern alt_u8 uart0_tx_state;//0״̬
int main()
{
	alt_u8 rx_len = 0;//յݳ
	uart0_tx_state = UART_TX_IDLE;//ʼ״̬־Ϊ
	//ʼLED
	LED_HANDLE hLED;
	hLED = LED_Init(PIO_LED_BASE);
	if (!hLED) {
		//printf("Failed to init LED\n");
	}
	//ʼ0
	UART_HANDLE hUART0;
	hUART0 = UART_Init(
			UART_BASE,
			UART_IRQ_INTERRUPT_CONTROLLER_ID,
			UART_IRQ,
			(IRRDY_IRQ_MASK),//򿪽жʹ0X80
			115200,//ڲ
			(alt_isr_func)UART0_isr
		);
	if (!hUART0) {
		//printf("Failed to init UART0\n");
	}
	while(1){
		//
		UARTx_Tx(hUART0, (alt_u8 *)"NIOS II!\n",sizeof("NIOS II!\n"));
		uart0_tx_state = UART_TX_BUSY;//Ǵ0״̬Ϊæ
		//ȡڽ
		rx_len = UARTx_Rx(hUART0, (alt_u8 *)data_tmp);
		if(rx_len)	//յ
		{
			//0æһֱȴ,ڷ
			while(uart0_tx_state == UART_TX_BUSY);
			//ͽյ
			UARTx_Tx(hUART0, (alt_u8 *)data_tmp, rx_len);
			uart0_tx_state = UART_TX_BUSY;//Ǵ0״̬Ϊæ
		}
		usleep(500000);
		LED_Toggle(hLED, LED3);//תled3ָʾϵͳ
		usleep(500000);//ʱ500ms
	}
  return 0;
}
