#include "sys.h"
#include "usart.h"
#include "delay.h"
#include "led.h"
#include "motor.h"
#include "yl_69.h"
#include "iic.h"
#include "FS2000.h"
#include "rs485.h"

#define TOTAL_WATER 200  //定量浇水

int main(void)
{
	
	float Liquid_dat = 0;//流速
	float total_water = 0;//水量
	u8 key;
	u32 lux;//存放光照强度数
  u8 luxfloat;//小数部分
	u8 luxint;//整数部分
	u8 i=0,t=0;
	u8 rs485buf[9]; 
	u8 command[3]={0xA5,0X09,0XAE};
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//设置系统中断优先级分组2
	delay_init(168);   //初始化延时函数
	
	uart_init(9600);
					//按键初始化  
	RS485_Init(9600);		//初始化RS485串口2
	 motor_init();
	 yl_69_init();
	 IIC_Init();
	 while(1)
	 {
	 
    //当湿度低于设定值，启动水泵		 
    while(SOIL_MOISTURE)
		{
			MOTOR_ON = 1;
			Liquid_dat = ReadLiquid();
			delay_ms(500);
			total_water = total_water+0.5*Liquid_dat;
			if(((int)total_water >= TOTAL_WATER))
			{
			  MOTOR_ON = 0;
        break;				
			}
			if(SOIL_MOISTURE==0)
			{
			   MOTOR_ON = 0;
          break;	
			}
		
		   
		 
		}
		
		if(SOIL_MOISTURE)
				 MOTOR_ON = 1;
			 else
				 MOTOR_ON = 0;
	 
			 
		 t++;
		delay_ms(1000);
		if(t==10)
		{
		
			for(i=0;i<3;i++)
			{
				rs485buf[i]=command[i];//发送指令
				
 			}
			RS485_Send_Data(rs485buf,3);//发送3个字节 									   
			t=0;
		}
		
		RS485_Receive_Data(rs485buf,&key);
		if(key)//接收到有数据
		{
			if(key>9)key=9;//最大是9个数据.
		}
		//当光照强度低于一定值时，开启LED灯
		lux=(rs485buf[5]<<16)+rs485buf[6]*256+rs485buf[7];
		luxfloat=lux%100;
    luxint=lux/100;
	
		if(luxint<10)	
       	LED_ON = 1; 	
	 }
	
 }

