0

我想使用 2 个计时器,一个用于读取传感器,另一个用于向机器人发出命令,使用 Visual Studio VC++ 2010 类库。

如果单击按钮 1,则第一个计时器打开,第二个计时器使用按钮 3。

但是当我单击按钮 2 时,即使我没有按下按钮 1,我的读取传感器也在工作,反之亦然。

这是我的程序:

我的代码有什么问题?

const int cTimer1 = 1;
const int cTimer2 = 1;

 void CENVSConfigDlg::OnBnClickedButton1()
{
SetTimer(cTimer1,1000,NULL);
}

 void CENVSConfigDlg::OnBnClickedButton2()
{
KillTimer(cTimer1);
}

 void CENVSConfigDlg::OnBnClickedButton3()
{   
SetTimer(cTimer2,10,NULL);  
}

void CENVSConfigDlg::OnBnClickedButton4()
{
    KillTimer(cTimer2);
}

void CENVSConfigDlg::OnTimer(UINT_PTR ID){
if(ID==cTimer1){

    char buffer[30],tempStr[5];
    int sensor[6];

    DWORD nbytes;

    MessageBeep(0);

    //Read Sensors

    if(!WriteFile( hnd_serial, "1", 1, &nbytes, NULL )){KillTimer(cTimer1);MessageBox(L"Write Com Port fail!");return;}
    Sleep(30);
    if(!ReadFile( hnd_serial, buffer, 30, &nbytes, NULL )){KillTimer(cTimer1);MessageBox(L"Read Com Port fail!");return;}
    Sleep(300);



if(ID==cTimer2)
{
    if(GetAsyncKeyState(0x53) != 0)
 {
 DWORD nbytes;
if(!WriteFile( hnd_serial, "s", 1, &nbytes, NULL )){MessageBox(L"Write Com Port fail!");return;}
    Sleep(30);
 tampil.SetWindowText( (LPCTSTR)"s" ); //backward
 }

else if(GetAsyncKeyState(0x57) != 0)
{
    DWORD nbytes;
if(!WriteFile( hnd_serial, "w", 1, &nbytes, NULL )){MessageBox(L"Write Com Port fail!");return;}
    Sleep(30);
    tampil.SetWindowText( (LPCTSTR)"w" );//forward
}


}

}


}
4

1 回答 1

0

发现自己的错误很好。但是您的代码仍然存在一些故障。

  • 您正在计时器(WM_TIMER消息)本身中执行读、写、睡眠。这将导致 UI 线程冻结。您最好使用另一个线程来处理,这涉及到 UI 更新以外的其他内容。
  • 您的计时器 ID 命名为等Timer1Timer2这对程序员不友好。您应该使用更好的名称来反映实际含义。
  • 多个计时器不会同时工作。同样,您最好使用多线程!
于 2013-04-06T09:36:11.990 回答