1. 程式人生 > >zigbee z-stack實現按鍵的長按

zigbee z-stack實現按鍵的長按

由於按鍵檢測有中斷、和輪詢兩種方式,預設採用輪詢方式,對於輪詢方式的長按處理比較簡單,利用鬆開的時間點和松下的時間點之間的時間差即可實現。對於中斷的方式可以採用定時器方式,當中斷觸發的時候,開一個定時器,如果定時器到期了,按鈕還是按下狀態,就認為是長按。

void InitBoard( uint8 level )
{
  if ( level == OB_COLD )
  {
    // Interrupts off
    osal_int_disable( INTS_ALL );
    // Turn all LEDs off
    //HalLedSet( HAL_LED_ALL, HAL_LED_MODE_OFF );
    // Check for Brown-Out reset
    ChkReset();
  }
  else  // !OB_COLD
  {
    /* Initialize Key stuff */
   // OnboardKeyIntEnable = HAL_KEY_INTERRUPT_DISABLE;//配置成輪
    OnboardKeyIntEnable = HAL_KEY_INTERRUPT_ENABLE;//配置成中斷
    HalKeyConfig( OnboardKeyIntEnable, OnBoard_KeyCallback);
  }
}


核心程式碼:

#define KEY_HOLD_LONG_INTERVAL  3
static uint32 keyPressTime = 0;

#define KEY_LONG_PRESS_TIME       1500     //3s
#define KEY_LONG_PRESS_MSG_EVT    0x005F


void SampleApp_HandleKeys( uint8 shift, uint8 keys )
{
  (void)shift;  // Intentionally unreferenced parameter
  
 
  if (!Hal_KeyIntEnable)//輪詢處理
  {
    if ( keys & HAL_KEY_SW_1 )//p0_1
    {
      
      if (keys == 0x01)//press down
      {
        keyPressTime = osal_getClock();
        
      }else //press up
      {
        
        if (keyPressTime)
        {
          keyPressTime = (osal_getClock() - keyPressTime);
          if (keyPressTime >= KEY_HOLD_LONG_INTERVAL )//長按
          {
            printf("long press... \r\n");      
          }
          else
          {
            printf("short press... \r\n");   
            HalLedSet(HAL_LED_G, HAL_LED_MODE_FLASH);
          }
          keyPressTime = 0;
        }
      }
    }else if ( keys & HAL_KEY_SW_2 )//p2_0
    {
      
    }
    
  }else{//中斷處理
    
    if ( keys & HAL_KEY_SW_1 )//p0_1
    {
	   //.....
       osal_stop_timerEx(SampleApp_TaskID,KEY_LONG_PRESS_MSG_EVT);
       osal_start_timerEx( SampleApp_TaskID, KEY_LONG_PRESS_MSG_EVT,
                          (KEY_LONG_PRESS_TIME));
		//.....
    }
   
  }
  
  
}

//定時器事件處理
uint16 SampleApp_ProcessEvent( uint8 task_id, uint16 events )
{
  afIncomingMSGPacket_t *MSGpkt;
  (void)task_id;

  //.....
  if ( events & KEY_LONG_PRESS_MSG_EVT ){
    
    printf("p1_0:%d ===\r\n",P0_1);
    if(P0_1 == 0){
       printf("p0_1 long press... \rn");
    }else{
      
    }
  }
  
  //....
  // Discard unknown events
  return 0;
}