我有一个控制灯泡的功能。只要按下按键,灯泡就会被编程为闪烁。但是,我想限制闪光之间的最小间隔,以防止灯泡烧坏。灯泡由连接到串口的继电器开关控制,代码如下:
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);
}
如何限制最小闪光间隔(以毫秒为单位)(毫秒精度非常重要)?
答案 0 :(得分:2)
您可以在该函数中保留一个静态变量,用于存储上次触发开关的时间。
然后您需要做的就是检查当前时间是否在此之后至少x毫秒。
您可以使用GetSystemTimeAsFileTime或GetSystemTime来获取当前时间戳,该时间戳应该具有毫秒分辨率。
答案 1 :(得分: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 :(得分: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);
}