visual c++ - 2 timer using OnTimer(UINT_PTR ID) with vc++ -
i want use 2 timer, 1 reading sensor, , give command robot, using visual studio vc++ 2010 class library.
first timer on if button 1 clicked, , second timer using button 3.
but when click button 2, read sensor working though have not press button 1, , vice versa.
here program:
what wrong code?
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 } } } }
it's found own mistake. code still has glitches.
- you performing read, write, sleep in timer (
wm_timer
message) itself. cause ui thread freeze. should better use thread process, involves other ui update. - your timer id named
timer1
,timer2
etc, not programmer friendly. should use better names reflect actual meaning. - multiple timers not work @ same time. again, better use multithreading!
Comments
Post a Comment