為了 layout 方便,把開關接到了沒有 IOC 的腳位上去,可以用掃描的方式來檢出開關的狀態。

程式很簡單,掃描的速度頗快....

不用 interrupt 程式更簡單:

struct

{

    uint8_t    negFlag :1;

    uint8_t    posFlag :1;

    uint8_t    swFlag :1;

    uint8_t    :5;

}switchFlag;

#define    negFlag    switchFlag.negFlag

#define    posFlag    switchFlag.posFlag

#define    swFlag    switchFlag.swFlag

 

void switchCheck(void)

{

//check switch
if(!SW && !negFalg && !posFlag)
{
    count = 0;         //first debounce count start.
    negFlag = 1;     //fall edge debounce be pressed.
}

//if time to complete, check switch again.
if(negFlag && !posFlag && count > DEBOUNCE_COUNT)
{
    if(!SW)
        posFlag = 1;     //debounce success, into next procedure.
    else
        negFlag = 0;     //debounce fail, clear debounce flag.
}

//wait switch pull high.
if(SW && negFlag && posFlag)
{
    swFlag = ~swFlag;   //change switch flag state.
    count = 0;                 //rise edge debounce count start.
    negFlag = 0;
}

//switch rise edge debounce success.
if(!negFlag && posFlag && count > DEBOUNCE_COUNT)
    posFlag = 0; //finish Debounce cycle.

}

SW 是直接接到開關的 GPIO,negFlag 及 posFlag 是表示檢出信號的旗標,swFlag 則是開關狀態的旗標。

DEBOUNCE_COUNT 是一個常數,和 debounce 的長度有關,要使 debounce 的時間為 20 msec。

計時器一樣是用 TMR0,如果中斷的時間是設成 1 msec,每次中斷時 count++,所以 DEBOUNCE_COUNT = 20。

 

創作者介紹
創作者 箱子裡的貓 的頭像
Bill Suen

箱子裡的貓

Bill Suen 發表在 痞客邦 留言(0) 人氣( 1364 )