代码整合

/*********************************************************************
 * INCLUDES
 */
#include 
#include 
#include "AF.h"
#include "OnBoard.h"
#include "OSAL_Tasks.h"
#include "SampleApp.h"
#include "ZDApp.h"
#include "ZDObject.h"
#include "ZDProfile.h"

#include "hal_drivers.h"
#include "hal_key.h"
#if defined ( LCD_SUPPORTED )
  #include "hal_lcd.h"
#endif
#include "hal_led.h"
#include "hal_uart.h"
#include "hal_adc.h"
//#include "ds1302.h"

#define DATA_PIN_INPUT  (P1DIR &= ~0x10)//p1_4口配置成输入模式
#define DATA_PIN_OUTPUT (P1DIR |= 0x10)

#define ds1302_sec_add			0x80		//秒数据地址
#define ds1302_min_add			0x82		//分数据地址
#define ds1302_hr_add			0x84		//时数据地址
#define ds1302_date_add			0x86		//日数据地址
#define ds1302_month_add		0x88		//月数据地址
#define ds1302_day_add			0x8a		//星期数据地址
#define ds1302_year_add			0x8c		//年数据地址
#define ds1302_control_add		0x8e		//控制数据地址
#define ds1302_charger_add		0x90 					 
#define ds1302_clkburst_add		0xbe
/*以前这里驱动不了ds1302终于知道为什么了
原来是lcd的驱动已经占用了P0_0口,再次定义IO P0_0会冲突
另外,由于P0_2口用作串口的RX脚,这样也会冲突
#define   RST P0_1   // DS1302复位
#define   IO P0_0
#define   SCK P0_3
*/
/*#define   RST P0_6   // DS1302复位
#define   IO P1_4
#define   SCK P0_7*/


/*********************************************************************
 * MACROS
 */

/*********************************************************************
 * CONSTANTS
 */
//当给不同的终端烧写代码的时候需要给宏赋相应的值,用以解开相应的资源
#define FLOWER  FALSE
#define KITCHEN FALSE
#define DOOR    TRUE
#define MEDICNE FALSE

#if ((KITCHEN == TRUE)||(FLOWER==TRUE))
 #include "DHT11.H"
   #if(FLOWER==TRUE)
    uint8 strTemp1[50]={0};//盆栽
   #endif
#else 
  uint8 strTemp2[60]={0};//厨房
  int len=0;
  //光照用
  uint8 buff[10]={0};
  byte len2=0;
  uint8 cnt = 0; 
  uint8 lcdstr[20] = {0};
#endif

#if (MEDICNE == TRUE)
 #include "MFRC522.H"
  unsigned char data2[4]  = {0x12,0,0,0};
  unsigned char DefaultKey[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 
  unsigned char g_ucTempbuf[20];    
  unsigned char MLastSelectedSnr[4];
  unsigned char RevBuffer[30];  
  unsigned char SerBuffer[20]; 
  unsigned char CmdValid; 
  unsigned char waitCommData=1;
  int data_len=0;
  int data_index=0;
#endif

#if !defined( SAMPLE_APP_PORT )
#define SAMPLE_APP_PORT  0
#endif

#if !defined( SAMPLE_APP_BAUD )
  #define SAMPLE_APP_BAUD  HAL_UART_BR_115200
#endif

// When the Rx buf space is less than this threshold, invoke the Rx callback.
#if !defined( SAMPLE_APP_THRESH )
#define SAMPLE_APP_THRESH  64
#endif

#if !defined( SAMPLE_APP_RX_SZ )
#define SAMPLE_APP_RX_SZ  40
#endif

#if !defined( SAMPLE_APP_TX_SZ )
#define SAMPLE_APP_TX_SZ  128
#endif

// Millisecs of idle time after a byte is received before invoking Rx callback.
#if !defined( SAMPLE_APP_IDLE )
#define SAMPLE_APP_IDLE  6
#endif

// Loopback Rx bytes to Tx for throughput testing.
#if !defined( SAMPLE_APP_LOOPBACK )
#define SAMPLE_APP_LOOPBACK  FALSE
#endif

// This is the max byte count per OTA message.
#if !defined( SAMPLE_APP_TX_MAX )
#define SAMPLE_APP_TX_MAX  35
#endif

#define SAMPLE_APP_RSP_CNT  4

// This list should be filled with Application specific Cluster IDs.
const cId_t SampleApp_ClusterList[SAMPLE_MAX_CLUSTERS] =
{
  SAMPLEAPP_P2P_CLUSTERID,
  SAMPLEAPP_PERIODIC_CLUSTERID,
  Door_CLUSTERID,
  Kitchen_CLUSTERID,
  FLOWER_CLUSTERID,
  MEDIENCE_CLUSTERID
};

const SimpleDescriptionFormat_t SampleApp_SimpleDesc =
{
  SAMPLEAPP_ENDPOINT,              //  int   Endpoint;
  SAMPLEAPP_PROFID,                //  uint16 AppProfId[2];
  SAMPLEAPP_DEVICEID,              //  uint16 AppDeviceId[2];
  SAMPLEAPP_DEVICE_VERSION,        //  int   AppDevVer:4;
  SAMPLEAPP_FLAGS,                 //  int   AppFlags:4;
  SAMPLE_MAX_CLUSTERS,          //  byte  AppNumInClusters;
  (cId_t *)SampleApp_ClusterList,  //  byte *pAppInClusterList;
  SAMPLE_MAX_CLUSTERS,          //  byte  AppNumOutClusters;
  (cId_t *)SampleApp_ClusterList   //  byte *pAppOutClusterList;
};

endPointDesc_t SampleApp_epDesc =
{
  SAMPLEAPP_ENDPOINT,
 &SampleApp_TaskID,
  (SimpleDescriptionFormat_t *)&SampleApp_SimpleDesc,
  noLatencyReqs
};

/*********************************************************************
 * TYPEDEFS
 */

//#define DATA_PIN P0_4            //定义P0.4口为传感器的输入端

/*********************************************************************
 * GLOBAL VARIABLES
 */
devStates_t SampleApp_NwkState;   
uint8 SampleApp_TaskID;           
//ds1302的变量              //秒    分   时   日   月  星期  年
//unsigned char write_addr[] = {0x80,0x82,0x84,0x86,0x88,0x8a,0x8c};
//nsigned char read_addr[] = {0x81,0x83,0x85,0x87,0x89,0x8b,0x8d};
typedef struct Date
{
  uint8 year;
  uint8 month;
  uint8 day;
  uint8 hour;
  uint8 minute;
  uint8 sec;
}Time;
Time open_time,close_time;
/*********************************************************************
 * EXTERNAL VARIABLES
 */

/*********************************************************************
 * EXTERNAL FUNCTIONS
 */

/*********************************************************************
 * LOCAL VARIABLES
 */

static uint8 SampleApp_MsgID;

afAddrType_t SampleApp_Periodic_DstAddr; //广播
afAddrType_t SampleApp_Flash_DstAddr;    //组播
afAddrType_t SampleApp_P2P_DstAddr;      //点播


static afAddrType_t SampleApp_TxAddr;
static uint8 SampleApp_TxSeq;
static uint8 SampleApp_TxBuf[SAMPLE_APP_TX_MAX+1];
static uint8 SampleApp_TxLen;

static afAddrType_t SampleApp_RxAddr;
static uint8 SampleApp_RxSeq;
static uint8 SampleApp_RspBuf[SAMPLE_APP_RSP_CNT];

/*********************************************************************
 * LOCAL FUNCTIONS
 */

static void SampleApp_ProcessMSGCmd( afIncomingMSGPacket_t *pkt );
void SampleApp_CallBack(uint8 port, uint8 event); 
#if !defined(ZDO_COORDINATOR)
static void SampleApp_Send_P2P_Message( void );
#endif
static void setBuzzer(uint8 on);
static void ds1302_init(void);
static void ds1302_write_byte(uint8 addr, uint8 d);
static uint8 ds1302_read_byte(uint8 addr);
static void ds1302_write_time(void);
static void ds1302_read_time(void);
static void Handle_Flower_Wen_Shi();
static void Handle_Kitchen_Wen_Shi();
static void Handle_Tu_Rang();
static uint8 GetSoilHum();
static uint8 GetMq2();
static uint8 GetFire();
static void Handle_MQ();
static void Handle_Fire();

/*********************************************************************
 * @fn      SampleApp_Init
 *
 * @brief   This is called during OSAL tasks' initialization.
 *
 * @param   task_id - the Task ID assigned by OSAL.
 *
 * @return  none
 */
void SampleApp_Init( uint8 task_id )
{
  halUARTCfg_t uartConfig;

  SampleApp_TaskID = task_id;
  SampleApp_RxSeq = 0xC3;
  SampleApp_NwkState = DEV_INIT;       

  MT_UartInit();                  //串口初始化
  MT_UartRegisterTaskID(task_id); //注册串口任务
  afRegister( (endPointDesc_t *)&SampleApp_epDesc );
  RegisterForKeys( task_id );
#if !defined(ZDO_COORDINATOR)//协调器可以不用编译下面代码
  #if(DOOR == TRUE) //这是厨房检测用到的引脚定义
     
  #endif
    
  #elif (FLOWER == TRUE) //土壤湿度要不要定义引脚啊?等会再来看
      P1SEL &= ~0x20;                 //设置P1.5为普通IO口
      P1DIR &= ~0x20;                 //P1.5定义为输入口
      
  #elif (MEDICNE == TRUE)//RFIF需要编译的
        P0DIR |= 0xF0; //P0_4、P0_5、P0_6、P0_7定义为输出
	P1DIR |= 0x21;//p1_0,P15输出

	P0 |= 0xF0; //P0_4、P0_5、P0_6、P0_7输出1
	P1 |= 0x21; //P1_0,P15输出高电平

        P0SEL &= ~0x40;                  //设置P0.6口为普通IO
        P0DIR &= ~0x40;                  //设置P0.6为输入

    
	CmdValid=0; 

	PcdReset();
	PcdAntennaOff(); 
	PcdAntennaOn();  
	M500PcdConfigISOType( 'A' );
        
  #elif(KITCHEN ==TRUE)
          P0SEL &= ~0x80;                 //设置P07为普通IO口
          P0DIR |= 0x80;                 //P07定义为输出口
          
          P1SEL &= ~0x20;                 //设置P1.5为普通IO口
          P1DIR &= ~0x20;                 //P1.5定义为输入口
          
          //P0SEL &= ~0x10;                 //设置P0.4为普通IO口
          //P0DIR &= ~0x10;                 //P0.4定义为输入口
          
          //下面这句代码是自己添加的
          P1SEL &= ~0x10;
          P1DIR &= ~0x10;                 //p1.4也定义为输入口     
      
#endif 
  SampleApp_Periodic_DstAddr.addrMode = (afAddrMode_t)AddrBroadcast;//广播
  SampleApp_Periodic_DstAddr.endPoint = SAMPLEAPP_ENDPOINT;
  SampleApp_Periodic_DstAddr.addr.shortAddr = 0xFFFF;

  // Setup for the flash command's destination address - Group 1
  SampleApp_Flash_DstAddr.addrMode = (afAddrMode_t)afAddrGroup;//组播
  SampleApp_Flash_DstAddr.endPoint = SAMPLEAPP_ENDPOINT;
  SampleApp_Flash_DstAddr.addr.shortAddr = SAMPLEAPP_FLASH_GROUP;
  
  SampleApp_P2P_DstAddr.addrMode = (afAddrMode_t)Addr16Bit; //点播 
  SampleApp_P2P_DstAddr.endPoint = SAMPLEAPP_ENDPOINT; 
  SampleApp_P2P_DstAddr.addr.shortAddr = 0x0000;            //发给协调器

  
}

/*********************************************************************
 * @fn      SampleApp_ProcessEvent
 *
 * @brief   Generic Application Task event processor.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events   - Bit map of events to process.
 *
 * @return  Event flags of all unprocessed events.
 */
UINT16 SampleApp_ProcessEvent( uint8 task_id, UINT16 events )
{
  (void)task_id;  // Intentionally unreferenced parameter
  
  if ( events & SYS_EVENT_MSG )
  {
    afIncomingMSGPacket_t *MSGpkt;

    while ( (MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( SampleApp_TaskID )) )
    {
      switch ( MSGpkt->hdr.event )
      {
      case AF_INCOMING_MSG_CMD:
        SampleApp_ProcessMSGCmd( MSGpkt );
        break;
        
      case ZDO_STATE_CHANGE:
        SampleApp_NwkState = (devStates_t)(MSGpkt->hdr.status);
        if ( SampleApp_NwkState == DEV_END_DEVICE )
        {
            /*HalUARTWrite(0,"Hi\r\n",3);
            HalUARTWrite(0,"你好\r\n",osal_strlen("你好\r\n"));
            HalUARTWrite(0,"你好ya\r\n",osal_strlen("你好ya\r\n")+1);
            HalUARTWrite(0,"你好o\r\n",osal_strlen("你好\r\n")-1);
            HalUARTWrite(0,"你好ws\r\n",strlen("你好ws\r\n"));
            HalUARTWrite(0,"你好hhh\r\n",osal_strlen("你好hhh\r\n")+1);
            HalUARTWrite(0,"你好eee\r\n",osal_strlen("你好eee\r\n")-1);
            HalUARTWrite(0,"ggg\r\n",5);
            HalUARTWrite(0,"kkk\r\n",6);*/ 
           osal_set_event(SampleApp_TaskID,SAMPLEAPP_SEND_PERIODIC_MSG_EVT);
        }      
        break;

      default:
        break;
      }

      osal_msg_deallocate( (uint8 *)MSGpkt );
    }

    return ( events ^ SYS_EVENT_MSG );
  }

  if ( events & SAMPLEAPP_SEND_PERIODIC_MSG_EVT )
  {
    osal_stop_timerEx(SampleApp_TaskID, SAMPLEAPP_SEND_PERIODIC_MSG_EVT);
#if !defined(ZDO_COORDINATOR)
    SampleApp_Send_P2P_Message(); 
#endif
    osal_start_timerEx( SampleApp_TaskID, SAMPLEAPP_SEND_PERIODIC_MSG_EVT,3000);
    return (events ^ SAMPLEAPP_SEND_PERIODIC_MSG_EVT);
  }


  return ( 0 );  // Discard unknown events.
}



/*********************************************************************
 * @fn      SerialApp_ProcessMSGCmd
 *
 * @brief   Data message processor callback. This function processes
 *          any incoming data - probably from other devices. Based
 *          on the cluster ID, perform the intended action.
 *
 * @param   pkt - pointer to the incoming message packet
 *
 * @return  TRUE if the 'pkt' parameter is being used and will be freed later,
 *          FALSE otherwise.
 */
uint8 flag1 = 2,flag2 = 2;//2代表未知状态,1代表寻到,0代表没寻到
void SampleApp_ProcessMSGCmd( afIncomingMSGPacket_t *pkt )
{
  uint8 buff[40]={0};

  switch ( pkt->clusterId )
  { 
  case MEDIENCE_CLUSTERID:
   uint8 card_status[30];
       if(pkt->cmd.DataLength==1)//当协调器收到长度为1 的空中数据
        {
          //sprintf(strr,"data[0]=%d\r\n",pkt->cmd.Data[0]);
          //HalUARTWrite(0,strr,strlen(strr)+1);
          if(pkt->cmd.Data[0] == 1)//如果发来的是1代表1号阅读器
          {
            if(flag1 != 0)//防止多次串口打印
            {
            sprintf(card_status,"1--Inventoury Failed\r\n");
            HalUARTWrite(0,card_status,strlen(card_status)+1);
            flag1 = 0;
            }
          }
          else if(pkt->cmd.Data[0]==2)
          {
            
            if(flag2 != 0)
            {
              sprintf(card_status,"2--Inventoury Failed\r\n");
              HalUARTWrite(0,card_status,strlen(card_status)+1);
              flag2 = 0;
            }
          } 
        }
        
        else if(pkt->cmd.DataLength==2)
        {
          //sprintf(strr,"data[0]=%d [1]=%d\r\n",pkt->cmd.Data[0],pkt->cmd.Data[1]);
          //HalUARTWrite(0,strr,strlen(strr)+1);
          if(pkt->cmd.Data[1]==1)
                { 
                  if(flag1 != 1)
                  {  
                    sprintf(card_status,"1--Inventoury Success\r\n");
                    HalUARTWrite(0,card_status,strlen(card_status)+1);
                    flag1 = 1;
                  }
                }
                else if(pkt->cmd.Data[1]==2)
                { 
                  if(flag2 != 1)
                  {
                    sprintf(card_status,"2--Inventoury Success\r\n");
                    HalUARTWrite(0,card_status,strlen(card_status)+1);
                    flag2 = 1;
                  }
                }          
        }
    break;

  case Kitchen_CLUSTERID:
       HalUARTWrite(0,pkt->cmd.Data, osal_strlen(pkt->cmd.Data));  
    break;
    
  case Door_CLUSTERID:
       HalUARTWrite(0,pkt->cmd.Data, osal_strlen(pkt->cmd.Data));
       HalLedBlink (HAL_LED_2,0, 60,1000);
    break;
    
  case FLOWER_CLUSTERID:
        HalUARTWrite(0,pkt->cmd.Data, osal_strlen(pkt->cmd.Data));
    break;
    
  default:
    break;
  }
}


/*********************************************************************
 * @fn      SampleApp_CallBack
 *
 * @brief   Send data OTA.
 *
 * @param   port - UART port.
 * @param   event - the UART port event flag.
 *
 * @return  none
 */
void SampleApp_CallBack(uint8 port, uint8 event)
{
  (void)port;

  if ((event & (HAL_UART_RX_FULL | HAL_UART_RX_ABOUT_FULL | HAL_UART_RX_TIMEOUT)) &&
//#if SAMPLE_APP_LOOPBACK
 //     (SampleApp_TxLen < SAMPLE_APP_TX_MAX))
//#else
      !SampleApp_TxLen)
//#endif
  {
    SampleApp_TxLen = HalUARTRead(SAMPLE_APP_PORT, SampleApp_TxBuf,34);
    /*uint8 j = 0;
    while(SampleApp_TxBuf[j] != 'o' && SampleApp_TxBuf[j] != 'c')
    {
      j++;
    }    
      uint8 i = 0;
      uint8 txbuff[50];
      while(SampleApp_TxBuf[j] != '#')
      {
        txbuff[i++] = SampleApp_TxBuf[j++];
      }
      txbuff[i] = '\r';
      txbuff[i+1] = '\n';
      txbuff[i+2] = '\0';
      i = 0;*/
      HalUARTWrite(port,SampleApp_TxBuf,osal_strlen(SampleApp_TxBuf)+1);
      AF_DataRequest( &SampleApp_P2P_DstAddr, &SampleApp_epDesc,
                       Door_CLUSTERID,
                       osal_strlen(SampleApp_TxBuf)+1,
                       SampleApp_TxBuf,
                       &SampleApp_MsgID,
                       AF_DISCV_ROUTE,
                       AF_DEFAULT_RADIUS );
    
    SampleApp_TxLen=0;
    osal_memset( SampleApp_TxBuf,0,SAMPLE_APP_TX_MAX+1);
    SampleApp_TxBuf[0] = '\0';
    
    //osal_memset( txbuff,0,50);
    //txbuff[0] = '\0';
  }
}
/*void SampleApp_CallBack(uint8 port, uint8 event)
{
  uint8 buff[128];
  uint8 i=0,j=0,flag=0;
  uint16 len = 0;
  while(Hal_UART_RxBufLen(port))
  {
    HalUARTRead(port,&buff[i++],1);
    flag = 1;
  }
  len  = Hal_UART_RxBufLen(0);
  if(flag == 1)
  {
    HalUARTWrite(port,"receive: ",osal_strlen("receive: ")+1);
    HalUARTWrite(port,buff,osal_strlen(buff)+1);
  AF_DataRequest( &SampleApp_P2P_DstAddr, &SampleApp_epDesc,
                       Door_CLUSTERID,
                       strlen(buff),
                       buff,
                       &SampleApp_MsgID,
                       AF_DISCV_ROUTE,
                       AF_DEFAULT_RADIUS );
  }
}*/
/*********************************************************************
 * @fn      SampleApp_Send_P2P_Message
 *
 * @brief   point to point.
 *
 * @param   none
 *
 * @return  none
 */
#if defined(ZDO_COORDINATOR)
//协调器没有必要编译下面的代码,节省资源
#else
void SampleApp_Send_P2P_Message( void )
{ 
#if(DOOR == TRUE) //这是厨房检测用到的引脚定义
     //do nothing,because all of thing only do at Serial loopback Func
   
#elif (FLOWER == TRUE) //土壤湿度要不要定义引脚啊?等会再来看
  #if defined(ZDO_COORDINATOR)//协调器可以不编译下面代码
    #else
        Handle_Flower_Wen_Shi();
        Handle_Tu_Rang();      
  #endif   

#elif(KITCHEN ==TRUE)
        Handle_Kitchen_Wen_Shi();
        Handle_Fire();
        Handle_MQ();  
        
#elif (MEDICNE == TRUE)//RFID需要编译的 
        uint8 SendBuf[10]={0};
        uint8 error=0;
        
        //寻卡命令
        RevBuffer[0]=0x02;
        RevBuffer[1]=0x26;

         // 寻卡
        iccardcode();

        if(RevBuffer[1]==0)//寻卡成功
        {
            //读卡命令
            SendBuf[0]=RevBuffer[2];  //data
            SendBuf[1]=RevBuffer[3];  //data        

            //找到卡
            //读卡
            RevBuffer[0]=0x03;
            iccardcode();

            if(RevBuffer[1]==0)
            {
                //读卡成功
                //记录卡ID
                SendBuf[2]=RevBuffer[2];  //data
                SendBuf[3]=RevBuffer[3];  //data
                SendBuf[4]=RevBuffer[4];  //data
                SendBuf[5]=RevBuffer[5];  //data
            }
            else
            {
                error=1;
            }
        }
        else
        {
            error=1;
        }

        if(error>0)
        {
            uint8 txbuf[1];
            //txbuf[0]=1;
            txbuf[0]=2;
            HalLcdWriteString( "Nothing or error", HAL_LCD_LINE_3 );
            AF_DataRequest( &SampleApp_P2P_DstAddr, &SampleApp_epDesc,
                       MEDIENCE_CLUSTERIDD,
                       1,
                       txbuf,
                       &SampleApp_MsgID,
                       AF_DISCV_ROUTE,
                       AF_DEFAULT_RADIUS);
            
        }
        else
        {
                uint8 txbuf[2];
                //输出显示
                PrintfRfidCard(SendBuf, 6);
               // txbuf[1] = 1;
                txbuf[1] = 2;
                
                //发送给协调器
                AF_DataRequest( &SampleApp_P2P_DstAddr, &SampleApp_epDesc,
                       MEDIENCE_CLUSTERID,
                       2,
                       txbuf,
                       &SampleApp_MsgID,
                       AF_DISCV_ROUTE,
                       AF_DEFAULT_RADIUS);
                
               
        }      
#endif
}
#endif


#if (FLOWER == TRUE)
//盆栽检测需要用到的函数,如果没定义FLOWER == TRUE就不会编译下面代码
void Handle_Flower_Wen_Shi()
{
    DHT11();//获取盆栽湿度   
    sprintf(strTemp1, "#flower#Humi:%d",shidu);
}

void Handle_Tu_Rang()
{ 
    uint8 str[10]={0};
    uint8 hum = GetSoilHum();
    sprintf(str, "#Soil:%d\r\n",hum);//土壤湿度
    strcat(strTemp1,str);
    uint8 ss[10] = {0};
    sprintf(ss,"air:%d soil:%d",shidu,hum);
    HalLcdWriteString (ss,HAL_LCD_LINE_3);
    
    AF_DataRequest( &SampleApp_P2P_DstAddr, 
                       &SampleApp_epDesc,
                       FLOWER_CLUSTERID,
                       osal_strlen(strTemp1),
                       strTemp1,
                       &SampleApp_MsgID,
                       AF_DISCV_ROUTE,
                       AF_DEFAULT_RADIUS );
}

//读取土壤的浓度
uint8 GetSoilHum()
{
  uint16 adc= 0;
  float vol=0.0; //adc采样电压  
  uint8 soil_hum=0;
  adc=HalAdcRead(HAL_ADC_CHANNEL_6, HAL_ADC_RESOLUTION_14); //土壤 ADC 采样值 P06口
  
  //最大采样值8192(因为最高位是符号位)
  if(adc>=8192)
  {
    return 0;
  }
  //不带YL-38的土壤湿度传感器需要将下面的注释
  adc=8192-adc;//反相一下,因为低湿度时AO口输出较高电平
               //高湿度时AO口输出较低电平   
  
  //转化为百分比
  vol=(float)((float)adc)/8192.0;
  //土壤百分比的整数值
  soil_hum=vol*100;
  return soil_hum;
}
//---------------------------------------
#endif


#if((KITCHEN ==TRUE))
/*厨房需要用到的函数*/
void Handle_Kitchen_Wen_Shi()
{
    DHT11();//获取温湿度
    sprintf(strTemp2, "#kitchen#Tempture:%d",wendu);//给终端1使用
    sprintf(lcdstr,"T:%d ",wendu);
}
//对火焰进行检测处理
void Handle_Fire()
{
  uint8 str[20]={0};
  uint8 has_fire = 0,fire;
  has_fire = P1_5 > 0?0:1;
  
  fire = GetFire();
  if(has_fire == 1)
  {
    sprintf(str, "#Fire:%d --True ",fire);
    uint8 strtmp[5]={0};
    sprintf(strtmp,"F:%d ",fire);
    strcat(lcdstr,strtmp);
  }
  else if(buff[0] == 0)
  {
    sprintf(str, "#Fire:%d --False",fire); 
    strcat(lcdstr,"F:0 ");
  }
  
  strcat(strTemp2,str);
}
//对可燃气体进行处理,最终将整理好的strtemp发送给协调器
void Handle_MQ()
{
    uint8 str[20]={0};
    uint8 has_MQ = 0,MQ;
    MQ = GetMq2();
    has_MQ = P1_4 > 0?0:1;
    
    if(has_MQ > 0) 
    {
     sprintf(str, "#MQ7:%d --True \r\n",MQ);

     uint8 strtmp[5]={0};
     sprintf(strtmp,"MQ:%d",MQ);
     strcat(lcdstr,strtmp);
    }
    else if(has_MQ == 0)
    {
     sprintf(str, "#MQ7:%d --False\r\n",MQ);
     strcat(lcdstr,"MQ:0");
    }
    HalLcdWriteString (lcdstr,HAL_LCD_LINE_3);
    strcat(strTemp2,str);
    AF_DataRequest( &SampleApp_P2P_DstAddr, 
                       &SampleApp_epDesc,
                       Kitchen_CLUSTERID,
                       osal_strlen(strTemp2),
                       strTemp2,
                       &SampleApp_MsgID,
                       AF_DISCV_ROUTE,
                       AF_DEFAULT_RADIUS );
  
}
//读取火焰的大小
uint8 GetFire()
{
  uint16 adc= 0;
  float vol=0.0; //adc采样电压  
  uint8 fire=0;
  adc=HalAdcRead(HAL_ADC_CHANNEL_6, HAL_ADC_RESOLUTION_14);//火焰 ADC 采样值 P06口
  
  //最大采样值8192(因为最高位是符号位)
  if(adc>=8192)
  {
    return 0;
  }
  
  adc=8192-adc;//反相一下,因为火焰小AO口输出较高电平
     //          火焰大时AO口输出较低电平   
  
  //转化为百分比
  vol=(float)((float)adc)/8192.0;
  
  //火焰百分比的整数值
  fire=vol*100;
  return fire;
}

//读取MQ2的浓度
uint8 GetMq2()
{
  uint16 adc= 0;
  float vol=0.0; //adc采样电压  
  uint8 percent=0;//百分比的整数值

  //读MQ2浓度
  adc= HalAdcRead(HAL_ADC_CHANNEL_4, HAL_ADC_RESOLUTION_14);

  //最大采样值8192(因为最高位是符号位)
  //2的13次方=8192
  if(adc>=8192)
  {
    return 0;
  }

  //转化为百分比
  vol=(float)((float)adc)/8192.0;
     
  //取百分比两位数字
  percent=vol*100;

  return percent;
}
//------------------------------------
#endif

/*
//DS1302初始化函数
void ds1302_init(void) 
{
	RST=0;			//RST脚置低
	SCK=0;			//SCK脚置低
}
//向DS1302写入一字节数据
void ds1302_write_byte(uint8 addr, uint8 d) 
{
	uint8 i;
	RST=1;					//启动DS1302总线	
	DATA_PIN_OUTPUT;
        //写入目标地址:addr
	addr = addr & 0xFE;   //最低位置零,寄存器0位为0时写,为1时读
	for (i = 0; i < 8; i ++) {
		if (addr & 0x01) {
			IO=1;
			}
		else {
			IO=0;
			}
		SCK=1;      //产生时钟
		SCK=0;
		addr = addr >> 1;
		}	
	//写入数据:d
	for (i = 0; i < 8; i ++) {
		if (d & 0x01) {
			IO=1;
			}
		else {
			IO=0;
			}
		SCK=1;    //产生时钟
		SCK=0;
		d = d >> 1;
		}
	RST=0;		//停止DS1302总线
}

//从DS1302读出一字节数据
uint8 ds1302_read_byte(uint8 addr) {

	uint8 i,temp;	
	RST=1;					//启动DS1302总线
	DATA_PIN_OUTPUT;
        //写入目标地址:addr
	addr = addr | 0x01;    //最低位置高,寄存器0位为0时写,为1时读
	for (i = 0; i < 8; i ++) {
		if (addr & 0x01) {
			IO=1;
			}
		else {
			IO=0;
			}
		SCK=1;
		SCK=0;
		addr = addr >> 1;
		}	
        DATA_PIN_INPUT;
        P1INP |= 0x01;//p00口配置成输入模式下的三态
	//输出数据:temp
	for (i = 0; i < 8; i ++) {
		temp = temp >> 1;
		if (IO) {
			temp |= 0x80;
			}
		else {
			temp &= 0x7F;
			}
		SCK=1;
		SCK=0;
		}	
	RST=0;					//停止DS1302总线
	return temp;
}
//向DS302写入时钟数据
void ds1302_write_time(void) 
{
		//打开写保护     
}
//从DS302读出时钟数据
void ds1302_read_time(void)  
{
  uint8 temp;
  temp = ds1302_read_byte(ds1302_year_add);//年 
        close_time.year = (temp >> 4)*10 + (temp&0x0f);
  temp = ds1302_read_byte(ds1302_year_add);//月 	
        close_time.month = (temp >> 4)*10+ (temp&0x0f);
  temp = ds1302_read_byte(ds1302_date_add);//日 	
        close_time.day = (temp >> 4)*10+ (temp&0x0f);		
  temp = ds1302_read_byte(ds1302_hr_add);//时 
        close_time.hour = (temp >> 4)*10+ (temp&0x0f);
  temp = ds1302_read_byte(ds1302_min_add);//分 
        close_time.minute = (temp >> 4)*10+ (temp&0x0f);
  temp = ds1302_read_byte(ds1302_sec_add)&0x7f;//秒,屏蔽秒的第7位,避免超出59
	close_time.sec = (temp >> 4)*10+ (temp&0x0f);
}*/

 

你可能感兴趣的:(zigbee学习)