我正在编写一个控制闪光灯的程序。闪光灯响应用户的按键而闪光。我试图限制闪光灯的出现规律性,以防止灯泡烧坏。我已经从这个论坛得到了一些帮助,但我无法用自己的代码实现代码。用户建议使用类,如下所示:
class bulb
{
__int64 clocks;
__int64 frequency;
public:
bulb()
{
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
frequency = li.QuadPart;
clocks = 0;
}
void WINAPI flash (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
// If this is the first occurence, set the 'clocks' to system time (+10000 to allow flash to occur)
if (clocks == 0) clocks = li.QuadPart + 10000;
__int64 timepassed = clocks - li.QuadPart;
if (timepassed >= (((double)frequency) / 10000))
{
//Set the clock
clocks = li.QuadPart;
//Define the serial port procedure
HANDLE hSerial;
//Open the serial port (fire the flash)
hSerial = CreateFile("COM1", GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
//Close the serial port
CloseHandle(hSerial);
}
}
};
我收到一些我似乎无法转移的语法错误,所有错误都在类的第一个或最后一个括号中 - “语法错误:标识符'灯泡'”,“语法错误:';' “,”语法错误:'}'“和”语法错误:'}'“。我之前从未使用过课程,所以期待这与此有关。我哪里错了?
请注意'10000'是闪光之间的最短延迟。
答案 0 :(得分:1)
您的代码存在一些主要问题:
HANDLE hSerial
。您正在线if (timepassed >= (((double)frequency) / 10000))
上错误地比较时间和频率。如果您希望将计数器从QueryPerformanceCounter
转换为实时,请使用以下内容:
double RealTime = (double) clocks / (double) frequency;
如果您收到其他错误消息,则它们与您发布的代码段之前或之后的代码相关。还有一些小问题和评论:
QueryPerformanceFrequency
和QueryPerformanceCounter
都可能失败。除非获得无效值并不重要,否则您应该检查这些值的返回值。if (clocks == 0)
应该全部在一行或包括括号,即:
if (clocks == 0) clocks = li.QuadPart + 10000;
if (clocks == 0) {
clocks = li.QuadPart + 10000;
}
编辑:将QueryPerformanceCounter转换为实时的示例(不包括错误检查):
LARGE_INTEGER Frequency;
LARGE_INTEGER Counter;
QueryPerformanceFrequency(&Frequency);
QueryPerformanceCounter(&Counter);
//Time in seconds
double RealTime = (double) Counter.QuadPart / (double)Frequency.QuadPart;
LARGE_INTEGER Counter1;
QueryPerformanceCounter(&Counter1);
//Elapsed time in seconds
double DeltaTime = (double) (Counter1.QuadPart - Counter.QuadPart) / (double)Frequency.QuadPart;
答案 1 :(得分:0)
在代码中的最后;
后添加}
class bulb
{
...
};