#define ALLOCATE_EXTERN
#include "bsp.h"
#include "modbusrtuslave.h"
#define DEATH_AERA 5
u16 avg_advalue[14]={0};
void update_IO_status(u8 index)
{
	u32 adc_sum=0;
	u8 newindex;
	u8 i;
	if(ModBus_Addr == 1){
		if(index < 3) return;
		else{
			newindex = index -3;
		}
	}else{
		newindex = index;
	}
	for(i=0;i<16;i++)
	{
		adc_sum += adcvalue[index][i];
	}
	adc_sum = adc_sum >>4;
	avg_advalue[newindex]=adc_sum;
	if(Modbus_HoldReg[newindex] < 4095 - DEATH_AERA && Modbus_HoldReg[newindex] > DEATH_AERA){
		if(adc_sum >= Modbus_HoldReg[newindex]+DEATH_AERA) Set_InputIO_Value(newindex,1);
		else if(adc_sum < Modbus_HoldReg[newindex]-DEATH_AERA) Set_InputIO_Value(newindex,0);

	}else{
		if(adc_sum >= Modbus_HoldReg[newindex]) Set_InputIO_Value(newindex,1);
		else if(adc_sum < Modbus_HoldReg[newindex]) Set_InputIO_Value(newindex,0);
	}
}
void main()
{
	bsp_init();
	Modbus_RTU_Init();
	
	while(1)
	{
		if(rs485_has_recv_timeout())
		{
			ModBusRtuSlave_Service(guc_Uartcnt);
			guc_Uartcnt =0;//清空接收缓冲区计数器
		}
		if(adc_full_complete==1)
		{
			update_IO_status(0);
			update_IO_status(1);
			update_IO_status(2);
			update_IO_status(3);
			update_IO_status(4);
			update_IO_status(5);
			update_IO_status(6);
			update_IO_status(7);
			update_IO_status(8);
			update_IO_status(9);
			update_IO_status(10);
			update_IO_status(11);
			update_IO_status(12);
			update_IO_status(13);
			adc_full_complete = 0;
			bsp_adc_start();
//			guc_UartTxbuf[0] = (u8)(adcvalue[0][0]>>8);
//			guc_UartTxbuf[1] = adcvalue[0][0];
//			bsp_uart_send_buff(2);
		}
	}
}

