2011-05-14 35 views
1

我有一個控制燈泡的功能。只要按下一個鍵,燈泡就會閃爍。但是,我想限制閃光燈之間的最短時間間隔以防止燈泡燒燬。燈泡由連接到串行端口的繼電器開關控制,並且代碼如下:限制事件的發生

void WINAPI flash (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nFunsterStil) 
{ 
    //MATT: Define the serial port procedure 
    HANDLE hSerial; 

    //MATT: Fire the flash (by initialising and uninitialising the port) 
    hSerial = CreateFile("COM1",GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); CloseHandle(hSerial); 
} 

如何限制在毫秒(毫秒精度是很重要的)的最小閃光間隔?

回答

2

您可以使用一個簡單的變量來保持QueryPerformanceCounter報告的時間。在大多數系統中,QPC的準確性非常高。在我的系統中,頻率爲280萬,或每十個處理器時鐘一個滴答。

class bulb { 
    __int64 clocks; 
    __int64 frequency; 
public: 
    static const int max_ms_between_flashes = 1; 
    bulb() { 
     LARGE_INTEGER li; 
     QueryPerformanceFrequency(&li); 
     frequency = li.QuadPart; 
     clocks = 0; 
    } 
    void flash(...) { 
     LARGE_INTEGER li; 
     QueryPerformanceCounter(&li); 
     if (clocks == 0) { 
      // We are the first time, so set the clocks var 
      // and flash the bulb 
      clocks = li.QuadPart;  
     } else { 
      __int64 timepassed = clocks - li.QuadPart; 
      if (timepassed >= (((double)frequency)/(max_ms_between_flashes * 1000))) { 
       // It's been more than 1ms 
       clocks = li.QuadPart; 
       // flash the bulb 
      } 
     } 
    } 
} 
2

您可以在該函數中保存一個靜態變量,存儲上一次觸發交換機的時間。

然後,您只需檢查當前時間是否在此時間後至少x毫秒。

您可以使用GetSystemTimeAsFileTimeGetSystemTime獲取當前時間戳,該時間戳應該具有毫秒分辨率。

0

如果你能閃爍之間的毫秒間隔存儲在一個全局變量,說FLASH_INETRVAL

void WINAPI flash (HINSTANCE hThisInstance, 
        HINSTANCE hPrevInstance, 
        LPSTR lpszArgument, 
        int nFunsterStil) 
    {    
     HANDLE hSerial; 
     static long lastFlashMillis; 
     // currentTimeMillis() should be defined using a system 
     // call that returns current 
     // system time in milliseconds. 
     long interval = currentTimeMillis() - lastFlashMillis; 

     if (interval < FLASH_INTERVAL) 
      Sleep (interval); 
     lastFlashMillis = currentTimeMillis(); 
     //MATT: Fire the flash (by initialising and uninitialising the port) 
     hSerial = CreateFile("COM1",GENERIC_WRITE, 0, 0, OPEN_EXISTING, 
          FILE_ATTRIBUTE_NORMAL, 0); CloseHandle(hSerial); 
    }